blob_id
stringlengths 40
40
| __id__
int64 225
39,780B
| directory_id
stringlengths 40
40
| path
stringlengths 6
313
| content_id
stringlengths 40
40
| detected_licenses
list | license_type
stringclasses 2
values | repo_name
stringlengths 6
132
| repo_url
stringlengths 25
151
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
70
| visit_date
timestamp[ns] | revision_date
timestamp[ns] | committer_date
timestamp[ns] | github_id
int64 7.28k
689M
⌀ | star_events_count
int64 0
131k
| fork_events_count
int64 0
48k
| gha_license_id
stringclasses 23
values | gha_fork
bool 2
classes | gha_event_created_at
timestamp[ns] | gha_created_at
timestamp[ns] | gha_updated_at
timestamp[ns] | gha_pushed_at
timestamp[ns] | gha_size
int64 0
40.4M
⌀ | gha_stargazers_count
int32 0
112k
⌀ | gha_forks_count
int32 0
39.4k
⌀ | gha_open_issues_count
int32 0
11k
⌀ | gha_language
stringlengths 1
21
⌀ | gha_archived
bool 2
classes | gha_disabled
bool 1
class | content
stringlengths 7
4.37M
| src_encoding
stringlengths 3
16
| language
stringclasses 1
value | length_bytes
int64 7
4.37M
| extension
stringclasses 24
values | filename
stringlengths 4
174
| language_id
stringclasses 1
value | entities
list | contaminating_dataset
stringclasses 0
values | malware_signatures
list | redacted_content
stringlengths 7
4.37M
| redacted_length_bytes
int64 7
4.37M
| alphanum_fraction
float32 0.25
0.94
| alpha_fraction
float32 0.25
0.94
| num_lines
int32 1
84k
| avg_line_length
float32 0.76
99.9
| std_line_length
float32 0
220
| max_line_length
int32 5
998
| is_vendor
bool 2
classes | is_generated
bool 1
class | max_hex_length
int32 0
319
| hex_fraction
float32 0
0.38
| max_unicode_length
int32 0
408
| unicode_fraction
float32 0
0.36
| max_base64_length
int32 0
506
| base64_fraction
float32 0
0.5
| avg_csv_sep_count
float32 0
4
| is_autogen_header
bool 1
class | is_empty_html
bool 1
class | shard
stringclasses 16
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
bc9b689b7632c4798e3e7bda5bbb55458db51181 | 31,044,023,661,428 | 2d21b53096bef751375bee5f532841df723bc59d | /tuan2/bai4/src/bai4/PhanSo.java | 3b6b0cc56f80aac54fc80d9bef402431e3f0b9d3 | []
| no_license | shichiki/BT2 | https://github.com/shichiki/BT2 | bd516dd8567c11a6e117ca5c24db77342858219d | 745fa11eec2afe5ba6b524330b7539e40163951a | refs/heads/master | 2021-01-10T04:18:29.227000 | 2016-04-06T17:56:29 | 2016-04-06T17:56:29 | 55,628,231 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package bai4;
public class PhanSo {
private int Tu_so;
private int Mau_So;
public PhanSo(int tu, int mau)
{//khoi tao Point co toa do xy
this.Tu_so = tu;
this.Mau_So= mau;
}
public PhanSo()
{//khoi tao voi toa so 0;0
this.Tu_so = 0;
this.Mau_So= 1;
}
public PhanSo(PhanSo p)
{//viet ra thui hem hieu co giong y cua de bai khong
this.Tu_so = p.Mau_So;
this.Tu_so = p.Mau_So;
}
//tao Set va get cho x va y
public int getX()
{
return Tu_so;
}
public int getY()
{
return Mau_So;
}
public void setX(int Tu_so) {
this.Tu_so = Tu_so;
}
public void setY(int Mau_So) {
this.Mau_So = Mau_So;
}
public PhanSo Tong(PhanSo b)
{
PhanSo kq = new PhanSo();
kq.Tu_so=this.Tu_so*b.Mau_So + b.Tu_so*this.Mau_So;
kq.Mau_So=this.Mau_So*b.Mau_So;
return kq;
}
public PhanSo Hieu(PhanSo b)
{
PhanSo kq = new PhanSo();
kq.Tu_so=this.Tu_so*b.Mau_So - b.Tu_so*this.Mau_So;
kq.Mau_So=this.Mau_So*b.Mau_So;
return kq;
}
public PhanSo Tich(PhanSo b)
{
PhanSo kq = new PhanSo();
kq.Tu_so = this.Tu_so*b.Tu_so;
kq.Mau_So=this.Mau_So*b.Mau_So;
return kq;
}
public PhanSo Thuong(PhanSo b)
{
PhanSo kq =new PhanSo();
kq.Tu_so =this.Tu_so*b.Mau_So;
kq.Mau_So=this.Mau_So*b.Tu_so;
return kq;
}
}
| UTF-8 | Java | 1,545 | java | PhanSo.java | Java | []
| null | []
| package bai4;
public class PhanSo {
private int Tu_so;
private int Mau_So;
public PhanSo(int tu, int mau)
{//khoi tao Point co toa do xy
this.Tu_so = tu;
this.Mau_So= mau;
}
public PhanSo()
{//khoi tao voi toa so 0;0
this.Tu_so = 0;
this.Mau_So= 1;
}
public PhanSo(PhanSo p)
{//viet ra thui hem hieu co giong y cua de bai khong
this.Tu_so = p.Mau_So;
this.Tu_so = p.Mau_So;
}
//tao Set va get cho x va y
public int getX()
{
return Tu_so;
}
public int getY()
{
return Mau_So;
}
public void setX(int Tu_so) {
this.Tu_so = Tu_so;
}
public void setY(int Mau_So) {
this.Mau_So = Mau_So;
}
public PhanSo Tong(PhanSo b)
{
PhanSo kq = new PhanSo();
kq.Tu_so=this.Tu_so*b.Mau_So + b.Tu_so*this.Mau_So;
kq.Mau_So=this.Mau_So*b.Mau_So;
return kq;
}
public PhanSo Hieu(PhanSo b)
{
PhanSo kq = new PhanSo();
kq.Tu_so=this.Tu_so*b.Mau_So - b.Tu_so*this.Mau_So;
kq.Mau_So=this.Mau_So*b.Mau_So;
return kq;
}
public PhanSo Tich(PhanSo b)
{
PhanSo kq = new PhanSo();
kq.Tu_so = this.Tu_so*b.Tu_so;
kq.Mau_So=this.Mau_So*b.Mau_So;
return kq;
}
public PhanSo Thuong(PhanSo b)
{
PhanSo kq =new PhanSo();
kq.Tu_so =this.Tu_so*b.Mau_So;
kq.Mau_So=this.Mau_So*b.Tu_so;
return kq;
}
}
| 1,545 | 0.50356 | 0.500324 | 75 | 19.6 | 14.521708 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.573333 | false | false | 15 |
f65b840a6265a6e7a3ab0e18bea19bccb8841865 | 31,344,671,354,976 | 6d3f7e1b367beb66573d646cbdf1c3dfc6dd8540 | /mall-common/src/main/java/com/mall/common/utils/CodeMsg.java | 6ac65b537be3073390d657957986bdaf3745c0d0 | []
| no_license | luolili/mall-demo | https://github.com/luolili/mall-demo | 8e33caf77d711ee89ae6aedaf2039c4ba8db9dae | 3497123df4bda2b790d1b51065167049a03fd186 | refs/heads/master | 2022-12-24T13:00:06.317000 | 2020-03-23T04:52:13 | 2020-03-23T04:52:13 | 202,844,647 | 0 | 0 | null | false | 2022-12-15T23:29:02 | 2019-08-17T06:28:35 | 2020-03-23T04:59:07 | 2022-12-15T23:28:59 | 202 | 0 | 0 | 11 | Java | false | false | package com.mall.common.utils;
import lombok.Data;
@Data
public class CodeMsg {
private int code;
private String msg;
private CodeMsg() {
}
private CodeMsg(int code, String msg) {
this.code = code;
this.msg = msg;
}
public CodeMsg fillArgs(Object... args) {
int code = this.code;
String msg = String.format(this.msg, args);
return new CodeMsg(code, msg);
}
public static CodeMsg SUCCESS = new CodeMsg(0, "success");
public static CodeMsg SERVER_ERROR = new CodeMsg(500100, "server_error");
public static CodeMsg REQUEST_ILLEGAL = new CodeMsg(500102, "request_illegal");
public static CodeMsg ACCESS_LIMIT = new CodeMsg(500103, "access_limit");
public static CodeMsg BIND_ERROR = new CodeMsg(500101, "%s");
//login
public static CodeMsg SESSION_ERROR = new CodeMsg(500210, "session_error");
public static CodeMsg MIAOSHA_FAIL = new CodeMsg(500210, "miaosha_fail");
public static CodeMsg PASSWORD_EMPTY = new CodeMsg(500211, "password_empty");
public static CodeMsg MOBILE_EMPTY = new CodeMsg(500212, "mobile_empty");
public static CodeMsg MOBILE_NOT_EXIST = new CodeMsg(500214, "mobile_not_exist");
public static CodeMsg PASSWORD_ERROR = new CodeMsg(500215, "password_error");
//item
public static CodeMsg success = new CodeMsg(0, "success");
//order
public static CodeMsg ORDER_NOT_EXIST = new CodeMsg(5004001, "订单不存在");
//public static CodeMsg success = new CodeMsg(0, "success");
//miaosha:5005XX
public static CodeMsg MIAOSHA_OVER = new CodeMsg(500500, "MIAOSHA_OVER");
public static CodeMsg MIAOSHA_GOODS_NOT_EXIST = new CodeMsg(500501, "MIAOSHA_GOODS_NOT_EXIST");
public static CodeMsg MIAOSHA_STOCK_NOT_ENOUGH = new CodeMsg(500501, "MIAOSHA_STOCK_NOT_ENOUGH");
public static CodeMsg MIAOSHA_STOCK_DECR_ERROR = new CodeMsg(500501, "MIAOSHA_STOCK_DECR_ERROR");
public static CodeMsg REPEATE_MIAOSHA = new CodeMsg(500510, "repeate_miaosha");
}
| UTF-8 | Java | 2,031 | java | CodeMsg.java | Java | []
| null | []
| package com.mall.common.utils;
import lombok.Data;
@Data
public class CodeMsg {
private int code;
private String msg;
private CodeMsg() {
}
private CodeMsg(int code, String msg) {
this.code = code;
this.msg = msg;
}
public CodeMsg fillArgs(Object... args) {
int code = this.code;
String msg = String.format(this.msg, args);
return new CodeMsg(code, msg);
}
public static CodeMsg SUCCESS = new CodeMsg(0, "success");
public static CodeMsg SERVER_ERROR = new CodeMsg(500100, "server_error");
public static CodeMsg REQUEST_ILLEGAL = new CodeMsg(500102, "request_illegal");
public static CodeMsg ACCESS_LIMIT = new CodeMsg(500103, "access_limit");
public static CodeMsg BIND_ERROR = new CodeMsg(500101, "%s");
//login
public static CodeMsg SESSION_ERROR = new CodeMsg(500210, "session_error");
public static CodeMsg MIAOSHA_FAIL = new CodeMsg(500210, "miaosha_fail");
public static CodeMsg PASSWORD_EMPTY = new CodeMsg(500211, "password_empty");
public static CodeMsg MOBILE_EMPTY = new CodeMsg(500212, "mobile_empty");
public static CodeMsg MOBILE_NOT_EXIST = new CodeMsg(500214, "mobile_not_exist");
public static CodeMsg PASSWORD_ERROR = new CodeMsg(500215, "password_error");
//item
public static CodeMsg success = new CodeMsg(0, "success");
//order
public static CodeMsg ORDER_NOT_EXIST = new CodeMsg(5004001, "订单不存在");
//public static CodeMsg success = new CodeMsg(0, "success");
//miaosha:5005XX
public static CodeMsg MIAOSHA_OVER = new CodeMsg(500500, "MIAOSHA_OVER");
public static CodeMsg MIAOSHA_GOODS_NOT_EXIST = new CodeMsg(500501, "MIAOSHA_GOODS_NOT_EXIST");
public static CodeMsg MIAOSHA_STOCK_NOT_ENOUGH = new CodeMsg(500501, "MIAOSHA_STOCK_NOT_ENOUGH");
public static CodeMsg MIAOSHA_STOCK_DECR_ERROR = new CodeMsg(500501, "MIAOSHA_STOCK_DECR_ERROR");
public static CodeMsg REPEATE_MIAOSHA = new CodeMsg(500510, "repeate_miaosha");
}
| 2,031 | 0.693716 | 0.642256 | 51 | 38.627453 | 34.186317 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.980392 | false | false | 15 |
de403abc3bad067dcf1c8615265581dd17bb590b | 31,344,671,354,532 | 8f9728f5cbcc13b6d759edb3f662ea2fb976a5fe | /src/controlador/OperacionesEmpleado.java | 3ea38454014be5f2cca258e6215534a00d68a99a | []
| no_license | lguille1991/ProyectoSTIS | https://github.com/lguille1991/ProyectoSTIS | 9c004882766a10f828a3ec8e1db4ab18c4f53dbe | 63a3079a87456115763285a0b52d356e3f30872e | refs/heads/master | 2021-01-23T11:03:55.167000 | 2017-06-05T11:12:31 | 2017-06-05T11:12:31 | 93,119,324 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package controlador;
import java.util.List;
/**
*
* @author Luis Martinez
*/
public interface OperacionesEmpleado {
public String agregarEmpleado(Object obj);
public String modificarEmpleado(Object obj);
public String eliminarEmpleado(Object obj);
public List llenarComboBox();
public List mostrarEmpleado();
}
| UTF-8 | Java | 351 | java | OperacionesEmpleado.java | Java | [
{
"context": ";\r\n\r\nimport java.util.List;\r\n\r\n/**\r\n *\r\n * @author Luis Martinez\r\n */\r\npublic interface OperacionesEmpleado {\r\n ",
"end": 83,
"score": 0.9996989369392395,
"start": 70,
"tag": "NAME",
"value": "Luis Martinez"
}
]
| null | []
| package controlador;
import java.util.List;
/**
*
* @author <NAME>
*/
public interface OperacionesEmpleado {
public String agregarEmpleado(Object obj);
public String modificarEmpleado(Object obj);
public String eliminarEmpleado(Object obj);
public List llenarComboBox();
public List mostrarEmpleado();
}
| 344 | 0.706553 | 0.706553 | 15 | 21.4 | 18.132109 | 48 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.466667 | false | false | 15 |
7e06682305ae7acd832c85fe7eb1f9b5614d499e | 26,448,408,677,236 | e9fd48a4bcbd356e6da42263959ea2f72c08f554 | /LibGdx-Core/src/main/java/libgdx/gui/dungeon/panels/dc/topleft/atb/AtbViewManager.java | ef649345d3b5660f316d21d1a760ac4f7d664cbb | []
| no_license | IDemiurge/Eidolons | https://github.com/IDemiurge/Eidolons | 453e74ab31cfdd12749cffddab0f7c2ff8e1b0d5 | 95398e80e18fbf566a5172c8e6343f38524fc7ec | refs/heads/dev | 2023-09-01T03:15:22.424000 | 2023-08-27T21:13:12 | 2023-08-27T21:13:12 | 71,926,671 | 6 | 0 | null | false | 2023-08-25T16:11:05 | 2016-10-25T18:25:50 | 2021-10-27T17:14:14 | 2023-08-25T16:11:05 | 66,676 | 9 | 0 | 17 | Java | false | false | package libgdx.gui.dungeon.panels.dc.topleft.atb;
import libgdx.anims.actions.ActionMasterGdx;
import libgdx.bf.generic.ImageContainer;
import libgdx.bf.grid.cell.QueueView;
import main.content.enums.GenericEnums;
import main.data.filesys.PathFinder;
import main.system.GuiEventManager;
import main.system.GuiEventType;
import main.system.PathUtils;
import main.system.auxiliary.StrPathBuilder;
import java.util.List;
public class AtbViewManager {
AtbPanel atbPanel;
public AtbViewManager(AtbPanel atbPanel) {
this.atbPanel = atbPanel;
bindEvents();
}
public void updateTimedEvents(){
/**
* need index to know where to draw, and that's it
*
*/
// timedEvents.for
}
protected void bindEvents() {
GuiEventManager.bind(GuiEventType.PREVIEW_ATB_READINESS, obj -> {
List<Integer> list = (List<Integer>) obj.get();
previewAtbReadiness(list);
});
GuiEventManager.bind(GuiEventType.ATB_POS_PREVIEW, obj -> {
if (obj.get() == null) {
removePreviewAtbPos();
previewAtbReadiness(null);
} else {
previewAtbPos((int) obj.get() );
}
});
}
protected void previewAtbReadiness(List<Integer> list) {
int i = 0;
for (int j =atbPanel. queue.length - 1; j > 0; j--) {
QueueViewContainer sub = atbPanel.queue[j];
if (sub == null)
break;
if (list != null)
if (list.size() <= i) {
break;
}
QueueView actor = sub.getActor();
String text = (list == null ? sub.initiative : list.get(i++)) + "";
if (actor == null) {
continue;
}
actor.setInitiativeLabelText(text);
}
}
void sort() {
for (int i = 0; i < atbPanel.queue.length - 1; i++) {
final int ip1 = i + 1;
QueueViewContainer cur = atbPanel.queue[i];
if (cur != null) {
QueueViewContainer next = atbPanel.queue[ip1];
if (next == null) {
atbPanel.queue[i] = null;
atbPanel.queue[ip1] = cur;
} else {
boolean result =
isSortByTimeTillTurn() ? cur.queuePriority > next.queuePriority || (cur.id > next.id && cur.queuePriority == next.queuePriority)
: cur.initiative > next.initiative || (cur.id > next.id && cur.initiative == next.initiative);
if (result) {
atbPanel.queue[ip1] = cur;
atbPanel.queue[i] = next;
for (int y = i; y > 0; y--) {
if (atbPanel.queue[y - 1] == null) {
break;
}
if (atbPanel.queue[y].initiative >= atbPanel.queue[y - 1].initiative) {
break;
}
QueueViewContainer buff = atbPanel.queue[y - 1];
atbPanel.queue[y - 1] = atbPanel.queue[y];
atbPanel.queue[y] = buff;
}
}
}
}
}
for (int i = 0; i < atbPanel.queue.length; i++) {
QueueViewContainer cur = atbPanel.queue[i];
if (cur != null && !cur.mobilityState) {
for (int y = i; y > 0; y--) {
if (atbPanel.queue[y - 1] == null) {
break;
}
if (!atbPanel.queue[y - 1].mobilityState) {
break;
}
QueueViewContainer buff = atbPanel.queue[y - 1];
atbPanel.queue[y - 1] = atbPanel.queue[y];
atbPanel.queue[y] = buff;
}
}
}
}
protected void previewAtbPos(int i) {
if (i > atbPanel.maxSize) {
//TODO
}
if (atbPanel.previewActor == null) {
atbPanel.addActor(atbPanel.previewActor = new ImageContainer(atbPanel.manager.getPreviewPath()));
atbPanel.previewActor.setAlphaTemplate(GenericEnums.ALPHA_TEMPLATE.ATB_POS);
}
atbPanel.previewActor.setVisible(true);
atbPanel.previewActor.setScale(1.25f);
atbPanel.previewActor.clearActions();
atbPanel.previewActor.setY(-30);
atbPanel.previewActor.setX(atbPanel.container.getX() + (i + 1) * (AtbPanel.imageSize + atbPanel.DST_BETWEEN_VIEWS) - atbPanel.DST_BETWEEN_VIEWS / 2);
ActionMasterGdx.addScaleActionCentered(atbPanel.previewActor, 0, 1, 8);
// ActorMaster.addMoveToAction(previewActor, previewActor.getX()+previewActor.getWidth()/2,
// previewActor.getY(), 5);
}
protected float relToPixPos(int pos) {
return pos * AtbPanel.imageSize + pos * atbPanel.DST_BETWEEN_VIEWS;
}
protected QueueViewContainer getIfExists(QueueView view) {
for (int i = 0; i < atbPanel.queue.length; i++) {
if (atbPanel.queue[i] != null && atbPanel.queue[i].getActor() == view) {
return atbPanel.queue[i];
}
}
return null;
}
protected QueueViewContainer getIfExists(int id) {
for (int i = 0; i < atbPanel.queue.length; i++) {
if (atbPanel.queue[i] != null && atbPanel.queue[i].id == id) {
return atbPanel.queue[i];
}
}
return null;
}
protected String getPreviewPath() {
return StrPathBuilder.build(PathFinder.getComponentsPath()
, "dc", "atb pos preview.png"
) + PathUtils.getPathSeparator();
}
protected boolean isSortByTimeTillTurn() {
return true;
}
protected void removePreviewAtbPos() {
if ( atbPanel.previewActor != null) {
atbPanel.previewActor.setVisible(false);
}
}
// public static class AtbTimedEvent{
//float timeLeft;
//boolean endOfRound;
//BattleFieldObject after;
//Runnable action;
// will this apply for Channeling?
// }
}
| UTF-8 | Java | 6,284 | java | AtbViewManager.java | Java | []
| null | []
| package libgdx.gui.dungeon.panels.dc.topleft.atb;
import libgdx.anims.actions.ActionMasterGdx;
import libgdx.bf.generic.ImageContainer;
import libgdx.bf.grid.cell.QueueView;
import main.content.enums.GenericEnums;
import main.data.filesys.PathFinder;
import main.system.GuiEventManager;
import main.system.GuiEventType;
import main.system.PathUtils;
import main.system.auxiliary.StrPathBuilder;
import java.util.List;
public class AtbViewManager {
AtbPanel atbPanel;
public AtbViewManager(AtbPanel atbPanel) {
this.atbPanel = atbPanel;
bindEvents();
}
public void updateTimedEvents(){
/**
* need index to know where to draw, and that's it
*
*/
// timedEvents.for
}
protected void bindEvents() {
GuiEventManager.bind(GuiEventType.PREVIEW_ATB_READINESS, obj -> {
List<Integer> list = (List<Integer>) obj.get();
previewAtbReadiness(list);
});
GuiEventManager.bind(GuiEventType.ATB_POS_PREVIEW, obj -> {
if (obj.get() == null) {
removePreviewAtbPos();
previewAtbReadiness(null);
} else {
previewAtbPos((int) obj.get() );
}
});
}
protected void previewAtbReadiness(List<Integer> list) {
int i = 0;
for (int j =atbPanel. queue.length - 1; j > 0; j--) {
QueueViewContainer sub = atbPanel.queue[j];
if (sub == null)
break;
if (list != null)
if (list.size() <= i) {
break;
}
QueueView actor = sub.getActor();
String text = (list == null ? sub.initiative : list.get(i++)) + "";
if (actor == null) {
continue;
}
actor.setInitiativeLabelText(text);
}
}
void sort() {
for (int i = 0; i < atbPanel.queue.length - 1; i++) {
final int ip1 = i + 1;
QueueViewContainer cur = atbPanel.queue[i];
if (cur != null) {
QueueViewContainer next = atbPanel.queue[ip1];
if (next == null) {
atbPanel.queue[i] = null;
atbPanel.queue[ip1] = cur;
} else {
boolean result =
isSortByTimeTillTurn() ? cur.queuePriority > next.queuePriority || (cur.id > next.id && cur.queuePriority == next.queuePriority)
: cur.initiative > next.initiative || (cur.id > next.id && cur.initiative == next.initiative);
if (result) {
atbPanel.queue[ip1] = cur;
atbPanel.queue[i] = next;
for (int y = i; y > 0; y--) {
if (atbPanel.queue[y - 1] == null) {
break;
}
if (atbPanel.queue[y].initiative >= atbPanel.queue[y - 1].initiative) {
break;
}
QueueViewContainer buff = atbPanel.queue[y - 1];
atbPanel.queue[y - 1] = atbPanel.queue[y];
atbPanel.queue[y] = buff;
}
}
}
}
}
for (int i = 0; i < atbPanel.queue.length; i++) {
QueueViewContainer cur = atbPanel.queue[i];
if (cur != null && !cur.mobilityState) {
for (int y = i; y > 0; y--) {
if (atbPanel.queue[y - 1] == null) {
break;
}
if (!atbPanel.queue[y - 1].mobilityState) {
break;
}
QueueViewContainer buff = atbPanel.queue[y - 1];
atbPanel.queue[y - 1] = atbPanel.queue[y];
atbPanel.queue[y] = buff;
}
}
}
}
protected void previewAtbPos(int i) {
if (i > atbPanel.maxSize) {
//TODO
}
if (atbPanel.previewActor == null) {
atbPanel.addActor(atbPanel.previewActor = new ImageContainer(atbPanel.manager.getPreviewPath()));
atbPanel.previewActor.setAlphaTemplate(GenericEnums.ALPHA_TEMPLATE.ATB_POS);
}
atbPanel.previewActor.setVisible(true);
atbPanel.previewActor.setScale(1.25f);
atbPanel.previewActor.clearActions();
atbPanel.previewActor.setY(-30);
atbPanel.previewActor.setX(atbPanel.container.getX() + (i + 1) * (AtbPanel.imageSize + atbPanel.DST_BETWEEN_VIEWS) - atbPanel.DST_BETWEEN_VIEWS / 2);
ActionMasterGdx.addScaleActionCentered(atbPanel.previewActor, 0, 1, 8);
// ActorMaster.addMoveToAction(previewActor, previewActor.getX()+previewActor.getWidth()/2,
// previewActor.getY(), 5);
}
protected float relToPixPos(int pos) {
return pos * AtbPanel.imageSize + pos * atbPanel.DST_BETWEEN_VIEWS;
}
protected QueueViewContainer getIfExists(QueueView view) {
for (int i = 0; i < atbPanel.queue.length; i++) {
if (atbPanel.queue[i] != null && atbPanel.queue[i].getActor() == view) {
return atbPanel.queue[i];
}
}
return null;
}
protected QueueViewContainer getIfExists(int id) {
for (int i = 0; i < atbPanel.queue.length; i++) {
if (atbPanel.queue[i] != null && atbPanel.queue[i].id == id) {
return atbPanel.queue[i];
}
}
return null;
}
protected String getPreviewPath() {
return StrPathBuilder.build(PathFinder.getComponentsPath()
, "dc", "atb pos preview.png"
) + PathUtils.getPathSeparator();
}
protected boolean isSortByTimeTillTurn() {
return true;
}
protected void removePreviewAtbPos() {
if ( atbPanel.previewActor != null) {
atbPanel.previewActor.setVisible(false);
}
}
// public static class AtbTimedEvent{
//float timeLeft;
//boolean endOfRound;
//BattleFieldObject after;
//Runnable action;
// will this apply for Channeling?
// }
}
| 6,284 | 0.52021 | 0.51464 | 180 | 33.91111 | 27.868797 | 157 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.544444 | false | false | 15 |
b313f78c1d39d4f2fc5f0b8b0a206e887b2f5e1d | 1,331,439,921,549 | 3e8014f34629518f9339c0e0285b81d867a1edbf | /src/main/java/com/net4w/proxy/dynamic/jdk/ITeacherDao.java | 7717cd2d379e5712ad65bb311631fbff0fb244e5 | []
| no_license | WangPingChun/design-pattern | https://github.com/WangPingChun/design-pattern | d250b0d06f0935b52d58c8104614a187271a4bb4 | cce3fd19ed86375e0139e92d6cd6c499882ec080 | refs/heads/master | 2023-08-14T18:59:31.400000 | 2020-05-23T15:32:03 | 2020-05-23T15:32:03 | 261,672,023 | 0 | 0 | null | false | 2023-07-23T15:15:50 | 2020-05-06T06:31:50 | 2020-05-23T16:00:18 | 2023-07-23T15:15:50 | 119 | 0 | 0 | 2 | Java | false | false | package com.net4w.proxy.dynamic.jdk;
/**
* @author WangPingChun
*/
public interface ITeacherDao {
void teach();
}
| UTF-8 | Java | 121 | java | ITeacherDao.java | Java | [
{
"context": "ckage com.net4w.proxy.dynamic.jdk;\n\n/**\n * @author WangPingChun\n */\npublic interface ITeacherDao {\n void teach",
"end": 65,
"score": 0.9996819496154785,
"start": 53,
"tag": "NAME",
"value": "WangPingChun"
}
]
| null | []
| package com.net4w.proxy.dynamic.jdk;
/**
* @author WangPingChun
*/
public interface ITeacherDao {
void teach();
}
| 121 | 0.68595 | 0.677686 | 8 | 14.125 | 13.401842 | 36 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 15 |
6a5e8a0f2a8b2bd0f546de8d6f0b00e8981df417 | 15,753,940,062,578 | 3879d8b2734179ddca0b5484c54ac0fb12ed73e6 | /src/main/java/com/jithin/ecommerce/services/CategoryService.java | 0ee2baca9ba1121550ce49885d8a947c6f48515c | []
| no_license | jithin0000/springecommmysql | https://github.com/jithin0000/springecommmysql | a5cfc3c6c7489ab33c9cad2fce0e0896d0cfcdaa | e93e34c3ea3754b986d3e6eb0f5721c01debc1d0 | refs/heads/master | 2020-12-18T20:49:58.363000 | 2020-01-29T06:35:42 | 2020-01-29T06:35:42 | 235,516,750 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.jithin.ecommerce.services;
import com.jithin.ecommerce.exception.CategoryNotFoundException;
import com.jithin.ecommerce.model.Category;
import com.jithin.ecommerce.repository.CategoryRepository;
import com.sun.xml.bind.v2.model.core.ID;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
@Service
public class CategoryService extends BaseService<CategoryRepository, Category> {
protected CategoryService(CategoryRepository repository) {
super(repository);
}
@Override
public Category update(Long id, Category body) {
Category category = getRepository().findById(id)
.orElseThrow(() -> new CategoryNotFoundException(id));
category.setName(body.getName());
Category newCategory = getRepository().save(category);
return newCategory;
}
public Page<Category> PaginatedCategoryList(int page, int size, String sort, String search){
Page<Category> categories = null;
if (!StringUtils.isEmpty(search))
{
categories = getRepository().findByNameContainingIgnoreCase(search, PageRequest.of(page, size, Sort.by(sort)));
}else {
categories = getRepository().findAll(PageRequest.of(page, size, Sort.by(sort)));
}
return categories;
}
}
| UTF-8 | Java | 1,482 | java | CategoryService.java | Java | []
| null | []
| package com.jithin.ecommerce.services;
import com.jithin.ecommerce.exception.CategoryNotFoundException;
import com.jithin.ecommerce.model.Category;
import com.jithin.ecommerce.repository.CategoryRepository;
import com.sun.xml.bind.v2.model.core.ID;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
@Service
public class CategoryService extends BaseService<CategoryRepository, Category> {
protected CategoryService(CategoryRepository repository) {
super(repository);
}
@Override
public Category update(Long id, Category body) {
Category category = getRepository().findById(id)
.orElseThrow(() -> new CategoryNotFoundException(id));
category.setName(body.getName());
Category newCategory = getRepository().save(category);
return newCategory;
}
public Page<Category> PaginatedCategoryList(int page, int size, String sort, String search){
Page<Category> categories = null;
if (!StringUtils.isEmpty(search))
{
categories = getRepository().findByNameContainingIgnoreCase(search, PageRequest.of(page, size, Sort.by(sort)));
}else {
categories = getRepository().findAll(PageRequest.of(page, size, Sort.by(sort)));
}
return categories;
}
}
| 1,482 | 0.720648 | 0.719973 | 47 | 30.531916 | 30.617649 | 123 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.617021 | false | false | 15 |
5999455a2e98edd9a2a11082f19c26b72b425c2b | 8,083,128,472,044 | e5b596bede1896d4b73b05422233921fce2985b3 | /2xg Server/src/server/model/players/packets/ItemClick3.java | 8decf7971d9a27b30a1ff97414cc854230c4f62b | []
| no_license | Monsterray/2xG-Server | https://github.com/Monsterray/2xG-Server | 2d8857507bc2f1b4d42639f96d1fd9b24045197e | 9b82c8340bdc99848dece3c64064379289e98866 | refs/heads/master | 2021-01-20T08:07:35.985000 | 2017-05-03T02:57:20 | 2017-05-03T02:57:20 | 90,101,451 | 3 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package server.model.players.packets;
import server.Config;
import server.model.players.Client;
import server.model.players.PacketType;
import server.model.players.skills.RuneCraft;
import server.util.Misc;
/**
* Item Click 3 Or Alternative Item Option 1
*
* @author
*
* Proper Streams
*/
public class ItemClick3 implements PacketType {
public void summon(Client c, int npcid){
if(c.hasFollower < 1){
c.Summoning().SummonNewNPC(npcid);
c.itsover = false;
c.deletedone = false;
} else {
c.sendMessage("You already have a NPC summoned");
c.sendMessage("To dismiss it you need to click on the summoning Stat icon");
c.itsover = false;
c.deletedone = false;
}
}
@Override
public void processPacket(Client c, int packetType, int packetSize) {
int itemId11 = c.getInStream().readSignedWordBigEndianA();
int itemId1 = c.getInStream().readSignedWordA();
int itemId = c.getInStream().readSignedWordA();
if(!c.getItems().playerHasItem(itemId, 1)) {
return;
}
c.s = itemId;
switch (itemId) {
case 4155:
c.sendMessage("You currently have "+c.pcPoints+" 2xG points.");
break;
case 995:
int cashAmount = c.getItems().getItemAmount(995);
if (c.inWild()) {
c.sendMessage("You cannot do this in the wilderness");
c.getPA().sendFrame126(""+c.MoneyCash+"", 8135);
return;
}
if(c.MoneyCash == 2147483647) {
c.sendMessage("Your pouch is full!");
return;
}
if ((c.MoneyCash + cashAmount) <= Config.MAXITEM_AMOUNT && (c.MoneyCash + cashAmount) > -1) {
if(cashAmount == 1) {
c.sendMessage("You add 1 coin to your pouch.");
} else {
c.sendMessage("You add "+cashAmount+" coins to your pouch.");
}
c.MoneyCash += cashAmount;
c.getItems().deleteItem(995, cashAmount);
if(c.MoneyCash > 99999 && c.MoneyCash <= 999999) {
c.getPA().sendFrame126(""+c.MoneyCash/1000+"K", 8134);
} else if(c.MoneyCash > 999999 && c.MoneyCash <= 100000000) {
c.getPA().sendFrame126(""+c.MoneyCash/1000000+"M", 8134);
} else if(c.MoneyCash > 1000000000 && c.MoneyCash <= 2147483647) {
c.getPA().sendFrame126(""+c.MoneyCash/1000000000 +"."+c.MoneyCash/1000000+"B", 8134);
} else {
c.getPA().sendFrame126(""+c.MoneyCash+"", 8134);
}
c.getPA().sendFrame126(""+c.MoneyCash+"", 8135);
return;
}
int Joker = c.MoneyCash-2147483647-cashAmount;
int DisIs = c.MoneyCash+cashAmount-2147483647;
int cash = c.MoneyCash;
if((c.MoneyCash + cashAmount) < 2147483647) {
cash += cashAmount;
c.getItems().deleteItem(995, cashAmount);
c.getItems().addItem(995, c.MoneyCash+cashAmount-2147483647);
cash = c.MoneyCash;
if(DisIs == 1) {
c.sendMessage("You add 1 coin to your pouch.");
} else {
c.sendMessage("You add "+Joker+" coins to your pouch.");
}
c.MoneyCash = 2147483647;
if(c.MoneyCash > 99999 && c.MoneyCash <= 999999) {
c.getPA().sendFrame126(""+c.MoneyCash/1000+"K", 8134);
} else if(c.MoneyCash > 999999 && c.MoneyCash <= 100000000) {
c.getPA().sendFrame126(""+c.MoneyCash/1000000+"M", 8134);
} else if(c.MoneyCash > 1000000000 && c.MoneyCash <= 2147483647) {
c.getPA().sendFrame126(""+c.MoneyCash/1000000000 +"."+c.MoneyCash/1000000+"B", 8134);
} else {
c.getPA().sendFrame126(""+c.MoneyCash+"", 8134);
}
c.getPA().sendFrame126(""+(c.MoneyCash*-1)+"", 8135);
return;
}
break;
case 1710:
c.getPA().handleGlory(itemId);
c.gloryValue = 2;
break;
case 1708:
c.getPA().handleGlory(itemId);
c.gloryValue = 1;
break;
case 1706:
c.getPA().handleGlory(itemId);
c.gloryValue = 0;
break;
case 1712:
c.getPA().handleGlory(itemId);
c.gloryValue = 3;
break;
case 1438:// Air Talisman
RuneCraft.locate(c, 2985, 3292);
c.getPA().startTeleport(2841, 4830, 0, "modern");
break;
case 1440:// Earth Talisman
RuneCraft.locate(c, 3306, 3474);
c.getPA().startTeleport(2655, 4830, 0, "modern");
break;
case 1442:// Fire Talisman
RuneCraft.locate(c, 3313, 3255);
c.getPA().startTeleport(2574, 4848, 0, "modern");
break;
case 1444:// Water Talisman
RuneCraft.locate(c, 3185, 3165);
c.getPA().startTeleport(2727, 4833, 0, "modern");
break;
case 1446:// Body Talisman
RuneCraft.locate(c, 3053, 3445);
c.getPA().startTeleport(2522, 4825, 0, "modern");
break;
case 1448:// Mind Talisman
RuneCraft.locate(c, 2982, 3514);
c.getPA().startTeleport(2792, 4827, 0, "modern");
break;
case 15707:
case 18817:
case 18823:
case 18821:
c.getPA().showInterface(29799);
break;
case 12007:
summon(c, 6795);
break;
case 12009:
summon(c, 6797);
break;
case 12011:
summon(c, 6799);
break;
case 12013:
summon(c, 6801);
break;
case 12015:
summon(c, 6803);
break;
case 12017:
summon(c, 6805);
break;
case 12019:
summon(c, 6807);
break;
case 12021:
summon(c, 6808);
break;
case 12023:
summon(c, 6810);
break;
case 12025:
summon(c, 6812);
break;
case 12027:
summon(c, 6993);
break;
case 12029:
summon(c, 6814);
break;
case 12031:
summon(c, 6816);
break;
case 12033:
summon(c, 6817);
break;
case 12035:
summon(c, 6819);
break;
case 12037:
summon(c, 6821);
break;
case 12039:
summon(c, 6823);
break;
case 12041:
summon(c, 6824);
break;
case 12043:
summon(c, 6826);
break;
case 12045:
summon(c, 6828);
break;
case 12047:
summon(c, 6830);
break;
case 12049:
summon(c, 6832);
break;
case 12051:
summon(c, 6834);
break;
case 12053:
summon(c, 6836);
break;
case 12055:
summon(c, 6838);
break;
case 12057:
summon(c, 6840);
break;
case 12059:
summon(c, 6842);
break;
case 12061:
summon(c, 6844);
break;
case 12063:
summon(c, 6995);
break;
case 12065:
summon(c, 6846);
break;
case 12067:
summon(c, 6848);
break;
case 12069:
summon(c, 6850);
break;
case 12071:
summon(c, 6852);
break;
case 12073:
summon(c, 6854);
break;
case 12075:
summon(c, 6856);
break;
case 12077:
summon(c, 6858);
break;
case 12079:
summon(c, 6860);
break;
case 12081:
summon(c, 6862);
break;
case 12083:
summon(c, 6864);
break;
case 12085:
summon(c, 6866);
break;
case 12087:
summon(c, 6868);
break;
case 12089:
summon(c, 6870);
break;
case 12091:
summon(c, 6872);
break;
case 12093:
summon(c, 6874);
break;
case 12123:
summon(c, 6890);
break;
case 12776:
summon(c, 7330);
break;
case 12778:
summon(c, 7332);
break;
case 12780:
summon(c, 7334);
break;
case 12782:
summon(c, 7336);
break;
case 12784:
summon(c, 7338);
break;
case 12786:
summon(c, 7340);
break;
case 12788:
summon(c, 7342);
break;
case 12790:
summon(c, 7344);
break;
case 12792:
summon(c, 7346);
break;
case 12794:
summon(c, 7348);
break;
case 12796:
summon(c, 7350);
break;
case 12798:
summon(c, 7352);
break;
case 12800:
summon(c, 7354);
break;
case 12802:
summon(c, 7356);
break;
case 12804:
summon(c, 7358);
break;
case 12806:
summon(c, 7360);
break;
case 12808:
summon(c, 7362);
break;
case 12810:
summon(c, 7364);
break;
case 12812:
summon(c, 7366);
break;
case 12814:
summon(c, 7368);
break;
case 12816:
summon(c, 7378);
break;
case 12818:
summon(c, 7371);
break;
case 12820:
summon(c, 7373);
break;
default:
if (c.playerRights == 3)
Misc.println(c.playerName+ " - Item3rdOption: "+itemId+" : "+itemId11+" : "+itemId1);
c.sendMessage("Doesn't Have a case please post on the forum the line below");
c.sendMessage("Item ID:"+ itemId +" ItemClick3");
break;
}
}
}
| UTF-8 | Java | 8,754 | java | ItemClick3.java | Java | []
| null | []
| package server.model.players.packets;
import server.Config;
import server.model.players.Client;
import server.model.players.PacketType;
import server.model.players.skills.RuneCraft;
import server.util.Misc;
/**
* Item Click 3 Or Alternative Item Option 1
*
* @author
*
* Proper Streams
*/
public class ItemClick3 implements PacketType {
public void summon(Client c, int npcid){
if(c.hasFollower < 1){
c.Summoning().SummonNewNPC(npcid);
c.itsover = false;
c.deletedone = false;
} else {
c.sendMessage("You already have a NPC summoned");
c.sendMessage("To dismiss it you need to click on the summoning Stat icon");
c.itsover = false;
c.deletedone = false;
}
}
@Override
public void processPacket(Client c, int packetType, int packetSize) {
int itemId11 = c.getInStream().readSignedWordBigEndianA();
int itemId1 = c.getInStream().readSignedWordA();
int itemId = c.getInStream().readSignedWordA();
if(!c.getItems().playerHasItem(itemId, 1)) {
return;
}
c.s = itemId;
switch (itemId) {
case 4155:
c.sendMessage("You currently have "+c.pcPoints+" 2xG points.");
break;
case 995:
int cashAmount = c.getItems().getItemAmount(995);
if (c.inWild()) {
c.sendMessage("You cannot do this in the wilderness");
c.getPA().sendFrame126(""+c.MoneyCash+"", 8135);
return;
}
if(c.MoneyCash == 2147483647) {
c.sendMessage("Your pouch is full!");
return;
}
if ((c.MoneyCash + cashAmount) <= Config.MAXITEM_AMOUNT && (c.MoneyCash + cashAmount) > -1) {
if(cashAmount == 1) {
c.sendMessage("You add 1 coin to your pouch.");
} else {
c.sendMessage("You add "+cashAmount+" coins to your pouch.");
}
c.MoneyCash += cashAmount;
c.getItems().deleteItem(995, cashAmount);
if(c.MoneyCash > 99999 && c.MoneyCash <= 999999) {
c.getPA().sendFrame126(""+c.MoneyCash/1000+"K", 8134);
} else if(c.MoneyCash > 999999 && c.MoneyCash <= 100000000) {
c.getPA().sendFrame126(""+c.MoneyCash/1000000+"M", 8134);
} else if(c.MoneyCash > 1000000000 && c.MoneyCash <= 2147483647) {
c.getPA().sendFrame126(""+c.MoneyCash/1000000000 +"."+c.MoneyCash/1000000+"B", 8134);
} else {
c.getPA().sendFrame126(""+c.MoneyCash+"", 8134);
}
c.getPA().sendFrame126(""+c.MoneyCash+"", 8135);
return;
}
int Joker = c.MoneyCash-2147483647-cashAmount;
int DisIs = c.MoneyCash+cashAmount-2147483647;
int cash = c.MoneyCash;
if((c.MoneyCash + cashAmount) < 2147483647) {
cash += cashAmount;
c.getItems().deleteItem(995, cashAmount);
c.getItems().addItem(995, c.MoneyCash+cashAmount-2147483647);
cash = c.MoneyCash;
if(DisIs == 1) {
c.sendMessage("You add 1 coin to your pouch.");
} else {
c.sendMessage("You add "+Joker+" coins to your pouch.");
}
c.MoneyCash = 2147483647;
if(c.MoneyCash > 99999 && c.MoneyCash <= 999999) {
c.getPA().sendFrame126(""+c.MoneyCash/1000+"K", 8134);
} else if(c.MoneyCash > 999999 && c.MoneyCash <= 100000000) {
c.getPA().sendFrame126(""+c.MoneyCash/1000000+"M", 8134);
} else if(c.MoneyCash > 1000000000 && c.MoneyCash <= 2147483647) {
c.getPA().sendFrame126(""+c.MoneyCash/1000000000 +"."+c.MoneyCash/1000000+"B", 8134);
} else {
c.getPA().sendFrame126(""+c.MoneyCash+"", 8134);
}
c.getPA().sendFrame126(""+(c.MoneyCash*-1)+"", 8135);
return;
}
break;
case 1710:
c.getPA().handleGlory(itemId);
c.gloryValue = 2;
break;
case 1708:
c.getPA().handleGlory(itemId);
c.gloryValue = 1;
break;
case 1706:
c.getPA().handleGlory(itemId);
c.gloryValue = 0;
break;
case 1712:
c.getPA().handleGlory(itemId);
c.gloryValue = 3;
break;
case 1438:// Air Talisman
RuneCraft.locate(c, 2985, 3292);
c.getPA().startTeleport(2841, 4830, 0, "modern");
break;
case 1440:// Earth Talisman
RuneCraft.locate(c, 3306, 3474);
c.getPA().startTeleport(2655, 4830, 0, "modern");
break;
case 1442:// Fire Talisman
RuneCraft.locate(c, 3313, 3255);
c.getPA().startTeleport(2574, 4848, 0, "modern");
break;
case 1444:// Water Talisman
RuneCraft.locate(c, 3185, 3165);
c.getPA().startTeleport(2727, 4833, 0, "modern");
break;
case 1446:// Body Talisman
RuneCraft.locate(c, 3053, 3445);
c.getPA().startTeleport(2522, 4825, 0, "modern");
break;
case 1448:// Mind Talisman
RuneCraft.locate(c, 2982, 3514);
c.getPA().startTeleport(2792, 4827, 0, "modern");
break;
case 15707:
case 18817:
case 18823:
case 18821:
c.getPA().showInterface(29799);
break;
case 12007:
summon(c, 6795);
break;
case 12009:
summon(c, 6797);
break;
case 12011:
summon(c, 6799);
break;
case 12013:
summon(c, 6801);
break;
case 12015:
summon(c, 6803);
break;
case 12017:
summon(c, 6805);
break;
case 12019:
summon(c, 6807);
break;
case 12021:
summon(c, 6808);
break;
case 12023:
summon(c, 6810);
break;
case 12025:
summon(c, 6812);
break;
case 12027:
summon(c, 6993);
break;
case 12029:
summon(c, 6814);
break;
case 12031:
summon(c, 6816);
break;
case 12033:
summon(c, 6817);
break;
case 12035:
summon(c, 6819);
break;
case 12037:
summon(c, 6821);
break;
case 12039:
summon(c, 6823);
break;
case 12041:
summon(c, 6824);
break;
case 12043:
summon(c, 6826);
break;
case 12045:
summon(c, 6828);
break;
case 12047:
summon(c, 6830);
break;
case 12049:
summon(c, 6832);
break;
case 12051:
summon(c, 6834);
break;
case 12053:
summon(c, 6836);
break;
case 12055:
summon(c, 6838);
break;
case 12057:
summon(c, 6840);
break;
case 12059:
summon(c, 6842);
break;
case 12061:
summon(c, 6844);
break;
case 12063:
summon(c, 6995);
break;
case 12065:
summon(c, 6846);
break;
case 12067:
summon(c, 6848);
break;
case 12069:
summon(c, 6850);
break;
case 12071:
summon(c, 6852);
break;
case 12073:
summon(c, 6854);
break;
case 12075:
summon(c, 6856);
break;
case 12077:
summon(c, 6858);
break;
case 12079:
summon(c, 6860);
break;
case 12081:
summon(c, 6862);
break;
case 12083:
summon(c, 6864);
break;
case 12085:
summon(c, 6866);
break;
case 12087:
summon(c, 6868);
break;
case 12089:
summon(c, 6870);
break;
case 12091:
summon(c, 6872);
break;
case 12093:
summon(c, 6874);
break;
case 12123:
summon(c, 6890);
break;
case 12776:
summon(c, 7330);
break;
case 12778:
summon(c, 7332);
break;
case 12780:
summon(c, 7334);
break;
case 12782:
summon(c, 7336);
break;
case 12784:
summon(c, 7338);
break;
case 12786:
summon(c, 7340);
break;
case 12788:
summon(c, 7342);
break;
case 12790:
summon(c, 7344);
break;
case 12792:
summon(c, 7346);
break;
case 12794:
summon(c, 7348);
break;
case 12796:
summon(c, 7350);
break;
case 12798:
summon(c, 7352);
break;
case 12800:
summon(c, 7354);
break;
case 12802:
summon(c, 7356);
break;
case 12804:
summon(c, 7358);
break;
case 12806:
summon(c, 7360);
break;
case 12808:
summon(c, 7362);
break;
case 12810:
summon(c, 7364);
break;
case 12812:
summon(c, 7366);
break;
case 12814:
summon(c, 7368);
break;
case 12816:
summon(c, 7378);
break;
case 12818:
summon(c, 7371);
break;
case 12820:
summon(c, 7373);
break;
default:
if (c.playerRights == 3)
Misc.println(c.playerName+ " - Item3rdOption: "+itemId+" : "+itemId11+" : "+itemId1);
c.sendMessage("Doesn't Have a case please post on the forum the line below");
c.sendMessage("Item ID:"+ itemId +" ItemClick3");
break;
}
}
}
| 8,754 | 0.552547 | 0.425977 | 473 | 16.507401 | 17.789124 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.38055 | false | false | 15 |
6ebf63b082c5a8bedc6d5cb0023aadcc17219a1e | 2,740,189,151,293 | 90c490b98938c65293e14bd062883efc32db3dac | /src/com/genericLib/ExcelLib.java | 24430dd93a1ca9101162bf1b7aae4511fa7ff88e | []
| no_license | pratikpadhi/Page_Object_Model | https://github.com/pratikpadhi/Page_Object_Model | c88d21ab4524edb88492fa35511970c4770e8e39 | f69226104bf929786b3e935d3d9f12fc67284671 | refs/heads/master | 2022-11-23T02:57:30.627000 | 2020-07-24T07:00:46 | 2020-07-24T07:00:46 | 282,062,162 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.genericLib;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
public class ExcelLib {
public String getExceldata(String filepath,String sheetname,int rownum,int colnum) throws EncryptedDocumentException, InvalidFormatException, IOException{
FileInputStream fis=new FileInputStream(filepath);
Workbook wb=WorkbookFactory.create(fis);
Sheet sh=wb.getSheet(sheetname);
Row rw=sh.getRow(rownum);
String data=rw.getCell(colnum).getStringCellValue();
System.out.println("come1");
return data;
}
public int countofdata(String filepath,String sheetname) throws EncryptedDocumentException, InvalidFormatException, IOException{
FileInputStream fis=new FileInputStream(filepath);
Workbook wb=WorkbookFactory.create(fis);
Sheet sh=wb.getSheet(sheetname);
int rowcount= sh.getLastRowNum();
return rowcount;
}
public void ReadExceldata(String filepath,String sheetname,int rownum,int colnum,String data) throws EncryptedDocumentException, InvalidFormatException, IOException{
FileInputStream fis=new FileInputStream(filepath);
Workbook wb=WorkbookFactory.create(fis);
Sheet sh=wb.getSheet(sheetname);
Row rw=sh.getRow(rownum);
Cell cel=rw.createCell(colnum);
cel.setCellType(cel.CELL_TYPE_STRING);
FileOutputStream fos=new FileOutputStream(filepath);
cel.setCellValue(data);
wb.write(fos);
wb.close();
}
public double getExceldatanum(String filepath,String sheetname,int rownum,int colnum) throws EncryptedDocumentException, InvalidFormatException, IOException{
FileInputStream fis=new FileInputStream(filepath);
Workbook wb=WorkbookFactory.create(fis);
Sheet sh=wb.getSheet(sheetname);
Row rw=sh.getRow(rownum);
double data=rw.getCell(colnum).getNumericCellValue();
return data;
}
public void ReadExceldatanum(String filepath,String sheetname,int rownum,int colnum,double data) throws EncryptedDocumentException, InvalidFormatException, IOException{
FileInputStream fis=new FileInputStream(filepath);
Workbook wb=WorkbookFactory.create(fis);
Sheet sh=wb.getSheet(sheetname);
Row rw=sh.getRow(rownum);
Cell cel=rw.createCell(colnum);
cel.setCellType(cel.CELL_TYPE_NUMERIC);
FileOutputStream fos=new FileOutputStream(filepath);
int e=(int)data;
cel.setCellValue(e);
wb.write(fos);
wb.close();
}
}
| UTF-8 | Java | 2,699 | java | ExcelLib.java | Java | []
| null | []
| package com.genericLib;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
public class ExcelLib {
public String getExceldata(String filepath,String sheetname,int rownum,int colnum) throws EncryptedDocumentException, InvalidFormatException, IOException{
FileInputStream fis=new FileInputStream(filepath);
Workbook wb=WorkbookFactory.create(fis);
Sheet sh=wb.getSheet(sheetname);
Row rw=sh.getRow(rownum);
String data=rw.getCell(colnum).getStringCellValue();
System.out.println("come1");
return data;
}
public int countofdata(String filepath,String sheetname) throws EncryptedDocumentException, InvalidFormatException, IOException{
FileInputStream fis=new FileInputStream(filepath);
Workbook wb=WorkbookFactory.create(fis);
Sheet sh=wb.getSheet(sheetname);
int rowcount= sh.getLastRowNum();
return rowcount;
}
public void ReadExceldata(String filepath,String sheetname,int rownum,int colnum,String data) throws EncryptedDocumentException, InvalidFormatException, IOException{
FileInputStream fis=new FileInputStream(filepath);
Workbook wb=WorkbookFactory.create(fis);
Sheet sh=wb.getSheet(sheetname);
Row rw=sh.getRow(rownum);
Cell cel=rw.createCell(colnum);
cel.setCellType(cel.CELL_TYPE_STRING);
FileOutputStream fos=new FileOutputStream(filepath);
cel.setCellValue(data);
wb.write(fos);
wb.close();
}
public double getExceldatanum(String filepath,String sheetname,int rownum,int colnum) throws EncryptedDocumentException, InvalidFormatException, IOException{
FileInputStream fis=new FileInputStream(filepath);
Workbook wb=WorkbookFactory.create(fis);
Sheet sh=wb.getSheet(sheetname);
Row rw=sh.getRow(rownum);
double data=rw.getCell(colnum).getNumericCellValue();
return data;
}
public void ReadExceldatanum(String filepath,String sheetname,int rownum,int colnum,double data) throws EncryptedDocumentException, InvalidFormatException, IOException{
FileInputStream fis=new FileInputStream(filepath);
Workbook wb=WorkbookFactory.create(fis);
Sheet sh=wb.getSheet(sheetname);
Row rw=sh.getRow(rownum);
Cell cel=rw.createCell(colnum);
cel.setCellType(cel.CELL_TYPE_NUMERIC);
FileOutputStream fos=new FileOutputStream(filepath);
int e=(int)data;
cel.setCellValue(e);
wb.write(fos);
wb.close();
}
}
| 2,699 | 0.789552 | 0.788811 | 72 | 36.486111 | 37.352299 | 169 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.375 | false | false | 15 |
b47a39ea559900ade9e65a783d32fe520d0e74e1 | 35,321,811,044,413 | f3d5cb18439cdf4ed117f3bbc80766e7ac9cd04c | /src/dao/StudentDao.java | 321cace87df66ae311d973cf3c7b5991e940c521 | []
| no_license | painye/webtest | https://github.com/painye/webtest | 55c433f752779ab86f52bbb274c3cc2bedfb0189 | 376f7308e871464f97579dda1c7a13c3fe20decd | refs/heads/master | 2023-02-22T20:49:22.189000 | 2021-01-24T07:30:47 | 2021-01-24T07:30:47 | 332,344,069 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package dao;
import entity.Student;
import util.JdbcUtil;
/**
* 该类实现了对jdbc底层的调用,数据库和数据之间的交换修改
*/
public class StudentDao {
/**
*该方法实现了往数据库中的student表中插入新的数据
* @param
* @return
*/
public static void main (String[] args ){
boolean flag = false;
Student stu=new Student();
stu.setSno("201215161");
stu.setSname("何肖钢");
stu.setSsex("女");
stu.setSdept("SD");
System.out.println(stu);
String sql = "insert into Student values (?, ?, ?, ?, ?)";
StudentDao sdao= new StudentDao();
sdao.login(stu);
}
public boolean insert(Student stu){
System.out.println(stu);
/*
String value="values (?, ?";
String sql = "insert into Student (sno, sname";
if(stu.getSsex()!=null) {
sql += ", ssex";
value += ", ?";
}
if(stu.getSage()!=null){
sql += ", sage";
value += ", ?";
}
if(stu.getSdept()!= null){
sql += ", sdept";
value += ", ?";
}
sql += ") ";
value += ")";
*/
String sql = "insert into Student values (?, ?, ?, ?, ?)";
JdbcUtil.getConnection();
boolean flag = JdbcUtil.insert(sql, stu);
JdbcUtil.closeConnection();
return flag;
}
public boolean login(Student stu){
String sql = "select * from Student where sno = ? and sname = ?";
JdbcUtil.getConnection();
boolean flag=JdbcUtil.login(sql, stu);
JdbcUtil.closeConnection();
return flag;
}
}
| UTF-8 | Java | 1,694 | java | StudentDao.java | Java | [
{
"context": ");\n stu.setSno(\"201215161\");\n stu.setSname(\"何肖钢\");\n stu.setSsex(\"女\");\n stu.setSdept(\"SD\");\n",
"end": 360,
"score": 0.9998232126235962,
"start": 357,
"tag": "NAME",
"value": "何肖钢"
}
]
| null | []
| package dao;
import entity.Student;
import util.JdbcUtil;
/**
* 该类实现了对jdbc底层的调用,数据库和数据之间的交换修改
*/
public class StudentDao {
/**
*该方法实现了往数据库中的student表中插入新的数据
* @param
* @return
*/
public static void main (String[] args ){
boolean flag = false;
Student stu=new Student();
stu.setSno("201215161");
stu.setSname("何肖钢");
stu.setSsex("女");
stu.setSdept("SD");
System.out.println(stu);
String sql = "insert into Student values (?, ?, ?, ?, ?)";
StudentDao sdao= new StudentDao();
sdao.login(stu);
}
public boolean insert(Student stu){
System.out.println(stu);
/*
String value="values (?, ?";
String sql = "insert into Student (sno, sname";
if(stu.getSsex()!=null) {
sql += ", ssex";
value += ", ?";
}
if(stu.getSage()!=null){
sql += ", sage";
value += ", ?";
}
if(stu.getSdept()!= null){
sql += ", sdept";
value += ", ?";
}
sql += ") ";
value += ")";
*/
String sql = "insert into Student values (?, ?, ?, ?, ?)";
JdbcUtil.getConnection();
boolean flag = JdbcUtil.insert(sql, stu);
JdbcUtil.closeConnection();
return flag;
}
public boolean login(Student stu){
String sql = "select * from Student where sno = ? and sname = ?";
JdbcUtil.getConnection();
boolean flag=JdbcUtil.login(sql, stu);
JdbcUtil.closeConnection();
return flag;
}
}
| 1,694 | 0.507519 | 0.50188 | 65 | 23.553846 | 17.120417 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.8 | false | false | 15 |
dcbbb01fbd7bfc2c7825bb7213f05b7e591b8285 | 35,278,861,372,899 | 8e3510add39cd77b8637df27ae977bc3b8182694 | /product-service/src/main/java/com/wetorek/cloud/productservice/repository/wrapper/CatalogClientWrapper.java | 234aa4edd8794ccf51cf439aff2fe611ae7c49c4 | []
| no_license | wetorek/microservices-inventory-application | https://github.com/wetorek/microservices-inventory-application | 07f1c0d7ff450e4f235bc4784818e80bc30f46cd | b79a6498f75cf4b13a386ee862bf16c11261634d | refs/heads/master | 2023-06-23T22:29:42.248000 | 2021-07-24T13:14:37 | 2021-07-24T13:14:37 | 389,103,580 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.wetorek.cloud.productservice.repository.wrapper;
import com.wetorek.cloud.productservice.domain.Product;
import com.wetorek.cloud.productservice.repository.CatalogFeignClient;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Optional;
@Component
@RequiredArgsConstructor
public class CatalogClientWrapper {
private final CatalogFeignClient catalogFeignClient;
public Optional<Product> getProductById(String uniq_Id) {
return Optional.of(catalogFeignClient.getProductById(uniq_Id));
}
public List<Product> getProductsBySku(String sku) {
return catalogFeignClient.getProductsBySku(sku)
.getProducts();
}
}
| UTF-8 | Java | 752 | java | CatalogClientWrapper.java | Java | []
| null | []
| package com.wetorek.cloud.productservice.repository.wrapper;
import com.wetorek.cloud.productservice.domain.Product;
import com.wetorek.cloud.productservice.repository.CatalogFeignClient;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Optional;
@Component
@RequiredArgsConstructor
public class CatalogClientWrapper {
private final CatalogFeignClient catalogFeignClient;
public Optional<Product> getProductById(String uniq_Id) {
return Optional.of(catalogFeignClient.getProductById(uniq_Id));
}
public List<Product> getProductsBySku(String sku) {
return catalogFeignClient.getProductsBySku(sku)
.getProducts();
}
}
| 752 | 0.784574 | 0.784574 | 24 | 30.333334 | 25.175495 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.416667 | false | false | 15 |
f065171ee42c94f7923ed0cd36f0284a1d3b7005 | 10,196,252,423,140 | eb9f655206c43c12b497c667ba56a0d358b6bc3a | /java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/convertSwitchToIf/beforeConcatInLabel.java | 8adb55febd3afd274a31798f5deac5d2547fe38b | [
"Apache-2.0"
]
| permissive | JetBrains/intellij-community | https://github.com/JetBrains/intellij-community | 2ed226e200ecc17c037dcddd4a006de56cd43941 | 05dbd4575d01a213f3f4d69aa4968473f2536142 | refs/heads/master | 2023-09-03T17:06:37.560000 | 2023-09-03T11:51:00 | 2023-09-03T12:12:27 | 2,489,216 | 16,288 | 6,635 | Apache-2.0 | false | 2023-09-12T07:41:58 | 2011-09-30T13:33:05 | 2023-09-12T03:37:30 | 2023-09-12T06:46:46 | 4,523,919 | 15,754 | 4,972 | 237 | null | false | false | // "Replace 'switch' with 'if'" "true-preview"
class Test {
void test(String str) {
<caret>switch (str) {
case "foo" + "bar":
}
}
} | UTF-8 | Java | 149 | java | beforeConcatInLabel.java | Java | []
| null | []
| // "Replace 'switch' with 'if'" "true-preview"
class Test {
void test(String str) {
<caret>switch (str) {
case "foo" + "bar":
}
}
} | 149 | 0.536913 | 0.536913 | 8 | 17.75 | 14.35923 | 46 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0 | false | false | 15 |
ae796d22c2dbe19fcd1a3bfc2c3c95d39400a6d9 | 18,889,266,226,979 | 3d6d1b916a7398eba3605210dab56e72f1bf4dd4 | /Step02_DataType/src/test/main/MainClass02.java | 64fffee00cb019f33da9958862b95e3620619acd | []
| no_license | guswl09/hello2 | https://github.com/guswl09/hello2 | 9be5078160683dfd483db085b67471f77291d8c3 | 891aea93aec04b324db168c7b2d3e9d325e1474f | refs/heads/master | 2022-09-07T18:16:24.197000 | 2020-05-28T00:54:39 | 2020-05-28T00:54:39 | 267,468,582 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package test.main;
public class MainClass02 {
public static void main(String[] args) {
//국어점수
int kor=95;
//영어점수
int eng=100;
//국어점수와 영어점수의 평균을 구해서 변수에 담고 그 결과를 콘솔창에 출력해 보세요.
//int type과 double type을 연산하면 결과는 double type이다.
double avg=(kor+eng)/2.0d;
System.out.println("평균:"+avg);
}
}
| UTF-8 | Java | 420 | java | MainClass02.java | Java | []
| null | []
| package test.main;
public class MainClass02 {
public static void main(String[] args) {
//국어점수
int kor=95;
//영어점수
int eng=100;
//국어점수와 영어점수의 평균을 구해서 변수에 담고 그 결과를 콘솔창에 출력해 보세요.
//int type과 double type을 연산하면 결과는 double type이다.
double avg=(kor+eng)/2.0d;
System.out.println("평균:"+avg);
}
}
| 420 | 0.662338 | 0.633117 | 15 | 19.533333 | 16.867588 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.666667 | false | false | 15 |
ed95f5e2407221c6b7fc6e106c012046104325f4 | 28,810,640,683,159 | ca1279ef15657c681201e5e7d59fdd99b4a9dbbe | /Chapter 3/Invoice/src/invoice/InvoiceTest.java | 345eca0666ae9a5e0a6abd3900f149f73614e62b | []
| no_license | jwiley0320/Java-How-to-Program-10th-Edition | https://github.com/jwiley0320/Java-How-to-Program-10th-Edition | 893e30d0915fdd2b74c4ddf3e98dad8e82543514 | d0cbba7a6dd3e4bb29d87df43ab86d2172fa4212 | refs/heads/master | 2020-11-26T17:34:28.688000 | 2020-01-13T02:45:46 | 2020-01-13T02:45:46 | 229,157,334 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package invoice;
/*
* Jason Matthew Wiley
* 12/14/2019
* Invoice Application
*
* Create a class called Invoice that a hardware store might use to represent an invoice
* for an item sold at the store. An Invoice should include four pieces of information as
* instance variables—a part number (type String), a part description (type String), a
* quantity of the item being purchased (type int) and a price per item (double). Your
* class should have a constructor that initializes the four instance variables. Provide
* a set and a get method for each instance variable. In addition, provide a method named
* getInvoiceAmount that calculates the invoice amount (i.e., multiplies the quantity by
* the price per item), then returns the amount as a double value. If the quantity is not
* positive, it should be set to 0. If the price per item is not positive, it should be
* set to 0.0. Write a test app named InvoiceTest that demonstrates class Invoice’s
* capabilities.
*/
public class InvoiceTest
{
public static void main(String[] args)
{
Invoice invoice = new Invoice("123", "Hammer", 2, 17.23);
//print to user Part Number: partNumber
System.out.printf("Part Number: %s\n", invoice.getPartNumber());
//print to user Part Description: partDescription
System.out.printf("Part Description: %s\n", invoice.getPartDescription());
//print to user Quantity: quantity
System.out.printf("Quantity: %s\n", invoice.getQuantity());
//print to user Price per Item: pricePerItem
System.out.printf("Price Per Item: $%.02f\n", invoice.getPricePerItem());
//print to user Invoice Amount: invoiceAmount
System.out.printf("Invoice Amount: $%.02f", invoice.getInvoiceAmount());
}
} | WINDOWS-1252 | Java | 1,763 | java | InvoiceTest.java | Java | [
{
"context": "package invoice;\r\n\r\n/*\r\n * Jason Matthew Wiley\r\n * 12/14/2019\r\n * Invoice Application\r\n * \r\n * C",
"end": 46,
"score": 0.999237060546875,
"start": 27,
"tag": "NAME",
"value": "Jason Matthew Wiley"
}
]
| null | []
| package invoice;
/*
* <NAME>
* 12/14/2019
* Invoice Application
*
* Create a class called Invoice that a hardware store might use to represent an invoice
* for an item sold at the store. An Invoice should include four pieces of information as
* instance variables—a part number (type String), a part description (type String), a
* quantity of the item being purchased (type int) and a price per item (double). Your
* class should have a constructor that initializes the four instance variables. Provide
* a set and a get method for each instance variable. In addition, provide a method named
* getInvoiceAmount that calculates the invoice amount (i.e., multiplies the quantity by
* the price per item), then returns the amount as a double value. If the quantity is not
* positive, it should be set to 0. If the price per item is not positive, it should be
* set to 0.0. Write a test app named InvoiceTest that demonstrates class Invoice’s
* capabilities.
*/
public class InvoiceTest
{
public static void main(String[] args)
{
Invoice invoice = new Invoice("123", "Hammer", 2, 17.23);
//print to user Part Number: partNumber
System.out.printf("Part Number: %s\n", invoice.getPartNumber());
//print to user Part Description: partDescription
System.out.printf("Part Description: %s\n", invoice.getPartDescription());
//print to user Quantity: quantity
System.out.printf("Quantity: %s\n", invoice.getQuantity());
//print to user Price per Item: pricePerItem
System.out.printf("Price Per Item: $%.02f\n", invoice.getPricePerItem());
//print to user Invoice Amount: invoiceAmount
System.out.printf("Invoice Amount: $%.02f", invoice.getInvoiceAmount());
}
} | 1,750 | 0.718022 | 0.704946 | 38 | 44.342106 | 34.615387 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.289474 | false | false | 15 |
d4e797c0c48ea2c07e4ebbb6b06f6000a4ee3e95 | 34,720,515,632,351 | aaec7c460dc9117913b3911e2dd10783c431cf57 | /src/main/java/com/dogus/Students.java | e37173a73a4861f053d33c984aca24c895774987 | []
| no_license | dogusakbulut/hello-world | https://github.com/dogusakbulut/hello-world | 367eef3f6a89d2d02c729ab05835c981bfe50710 | 760189f9f83340584ef9aed244f0924861235dc6 | refs/heads/master | 2016-08-11T10:26:02.493000 | 2016-03-06T11:12:17 | 2016-03-06T11:12:17 | 53,225,141 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.dogus;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
@ManagedBean(name = "students")
@ViewScoped
public class Students {
private List<Student> studentList = new LinkedList<>();
@PostConstruct
void init() {
studentList.add(new Student("Ali", "100", "1A"));
studentList.add(new Student("Veli", "101", "1A"));
studentList.add(new Student("Okan", "102", "1B"));
studentList.add(new Student("Furkan", "103", "2A"));
studentList.add(new Student("Eren", "104", "2B"));
studentList.add(new Student("Fatma", "105", "1A"));
studentList.add(new Student("Ayşe", "106", "1A"));
studentList.add(new Student("Arzu", "107", "1B"));
studentList.add(new Student("Murat", "108", "2A"));
studentList.add(new Student("Mehmet", "109", "3B"));
}
public List<Student> getStudentList() {
return studentList;
}
public void setStudentList(List<Student> studentList) {
this.studentList = studentList;
}
public boolean isInSameClass(Student student) {
return studentList.stream()
.filter(std -> !std.equals(student))
.anyMatch(std -> {
return std.getClazz().equals(student.getClazz());
});
}
public String getClassMates(Student student) {
return studentList.stream()
.filter(std -> !std.equals(student))
.filter(std -> std.getClazz().equals(student.getClazz()))
.map(std -> std.getName())
.collect(Collectors.joining(","));
}
}
| UTF-8 | Java | 1,606 | java | Students.java | Java | [
{
"context": "\n\tvoid init() {\r\n\r\n\t\tstudentList.add(new Student(\"Ali\", \"100\", \"1A\"));\r\n\t\tstudentList.add(new Student(\"",
"end": 434,
"score": 0.9998254179954529,
"start": 431,
"tag": "NAME",
"value": "Ali"
},
{
"context": "\", \"100\", \"1A\"));\r\n\t\tstudentList.add(new Student(\"Veli\", \"101\", \"1A\"));\r\n\t\tstudentList.add(new Student(\"",
"end": 488,
"score": 0.9993662238121033,
"start": 484,
"tag": "NAME",
"value": "Veli"
},
{
"context": "\", \"101\", \"1A\"));\r\n\t\tstudentList.add(new Student(\"Okan\", \"102\", \"1B\"));\r\n\t\tstudentList.add(new Student(\"",
"end": 542,
"score": 0.9997193813323975,
"start": 538,
"tag": "NAME",
"value": "Okan"
},
{
"context": "\", \"102\", \"1B\"));\r\n\t\tstudentList.add(new Student(\"Furkan\", \"103\", \"2A\"));\r\n\t\tstudentList.add(new Student(\"",
"end": 598,
"score": 0.9996538162231445,
"start": 592,
"tag": "NAME",
"value": "Furkan"
},
{
"context": "\", \"103\", \"2A\"));\r\n\t\tstudentList.add(new Student(\"Eren\", \"104\", \"2B\"));\r\n\t\tstudentList.add(new Student(\"",
"end": 652,
"score": 0.9995493292808533,
"start": 648,
"tag": "NAME",
"value": "Eren"
},
{
"context": "\", \"104\", \"2B\"));\r\n\t\tstudentList.add(new Student(\"Fatma\", \"105\", \"1A\"));\r\n\t\tstudentList.add(new Student(\"",
"end": 707,
"score": 0.9992092847824097,
"start": 702,
"tag": "NAME",
"value": "Fatma"
},
{
"context": "\", \"105\", \"1A\"));\r\n\t\tstudentList.add(new Student(\"Ayşe\", \"106\", \"1A\"));\r\n\t\tstudentList.add(new Student(\"",
"end": 761,
"score": 0.99955153465271,
"start": 757,
"tag": "NAME",
"value": "Ayşe"
},
{
"context": "\", \"106\", \"1A\"));\r\n\t\tstudentList.add(new Student(\"Arzu\", \"107\", \"1B\"));\r\n\t\tstudentList.add(new Student(\"",
"end": 815,
"score": 0.999663233757019,
"start": 811,
"tag": "NAME",
"value": "Arzu"
},
{
"context": "\", \"107\", \"1B\"));\r\n\t\tstudentList.add(new Student(\"Murat\", \"108\", \"2A\"));\r\n\t\tstudentList.add(new Student(\"",
"end": 870,
"score": 0.9995144009590149,
"start": 865,
"tag": "NAME",
"value": "Murat"
},
{
"context": "\", \"108\", \"2A\"));\r\n\t\tstudentList.add(new Student(\"Mehmet\", \"109\", \"3B\"));\r\n\r\n\t}\r\n\r\n\tpublic List<Student> g",
"end": 926,
"score": 0.9994974732398987,
"start": 920,
"tag": "NAME",
"value": "Mehmet"
}
]
| null | []
| package com.dogus;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
@ManagedBean(name = "students")
@ViewScoped
public class Students {
private List<Student> studentList = new LinkedList<>();
@PostConstruct
void init() {
studentList.add(new Student("Ali", "100", "1A"));
studentList.add(new Student("Veli", "101", "1A"));
studentList.add(new Student("Okan", "102", "1B"));
studentList.add(new Student("Furkan", "103", "2A"));
studentList.add(new Student("Eren", "104", "2B"));
studentList.add(new Student("Fatma", "105", "1A"));
studentList.add(new Student("Ayşe", "106", "1A"));
studentList.add(new Student("Arzu", "107", "1B"));
studentList.add(new Student("Murat", "108", "2A"));
studentList.add(new Student("Mehmet", "109", "3B"));
}
public List<Student> getStudentList() {
return studentList;
}
public void setStudentList(List<Student> studentList) {
this.studentList = studentList;
}
public boolean isInSameClass(Student student) {
return studentList.stream()
.filter(std -> !std.equals(student))
.anyMatch(std -> {
return std.getClazz().equals(student.getClazz());
});
}
public String getClassMates(Student student) {
return studentList.stream()
.filter(std -> !std.equals(student))
.filter(std -> std.getClazz().equals(student.getClazz()))
.map(std -> std.getName())
.collect(Collectors.joining(","));
}
}
| 1,606 | 0.658567 | 0.633645 | 57 | 26.157894 | 21.143444 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.017544 | false | false | 15 |
38ad1ea0aa8824376872742e997324fe9d36dd7a | 19,859,928,793,849 | 504a249a66d8e306f69e4ef029f48c1c6e16a64d | /src/main/java/com/creditease/crawler/models/FileAttachment.java | 55d98af2bbb50053928aeffc672ea4c4d3d2b74c | []
| no_license | iwbrhwfy/crawler | https://github.com/iwbrhwfy/crawler | 507afbc3733c7639bca6c644ce0d6cc1de1f8f51 | 0fad2248b1245e15bc9c5630c5f25427eddcc92b | refs/heads/master | 2020-02-25T02:26:57.447000 | 2017-06-12T09:53:54 | 2017-06-12T09:53:54 | 100,353,017 | 1 | 3 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.creditease.crawler.models;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import lombok.Data;
/**
* Created by kenshin on 2017/6/1.
*/
@Data
@Entity
@Table(name = "file_attachment")
public class FileAttachment extends BasicModel {
@Column(name = "file_type")
private String fileType;
@Column(name = "file_content", columnDefinition = "longtext")
private String fileContent;
}
| UTF-8 | Java | 463 | java | FileAttachment.java | Java | [
{
"context": "nce.Table;\n\nimport lombok.Data;\n\n/**\n * Created by kenshin on 2017/6/1.\n */\n\n@Data\n@Entity\n@Table(name = \"fi",
"end": 185,
"score": 0.9997109174728394,
"start": 178,
"tag": "USERNAME",
"value": "kenshin"
}
]
| null | []
| package com.creditease.crawler.models;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import lombok.Data;
/**
* Created by kenshin on 2017/6/1.
*/
@Data
@Entity
@Table(name = "file_attachment")
public class FileAttachment extends BasicModel {
@Column(name = "file_type")
private String fileType;
@Column(name = "file_content", columnDefinition = "longtext")
private String fileContent;
}
| 463 | 0.732181 | 0.719222 | 23 | 19.130434 | 18.538572 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.347826 | false | false | 15 |
731498ec437d267ab0871821beccc35ab74b0013 | 16,612,933,529,742 | 61c1e22a047e000b8ce35d67b8593f0d672fb801 | /3-collections/src/main/java/com/cooksys/ftd/assignments/collections/hierarchy/DoubleGen.java | 2b7fba2480179fc1834373d7a8a158f99005ef4d | []
| no_license | DanielVorn/combined-assignments | https://github.com/DanielVorn/combined-assignments | cdc5281c4153f013d9dba66ca82c198bbc0c1b8f | 58d9bff01eb951bfdd6b9f103be7bdaf81c600ae | refs/heads/master | 2019-04-28T10:24:13.319000 | 2017-02-27T21:36:51 | 2017-02-27T21:36:51 | 82,582,634 | 0 | 0 | null | true | 2017-02-20T17:12:00 | 2017-02-20T17:11:59 | 2016-10-06T22:04:35 | 2016-10-28T14:45:56 | 73 | 0 | 0 | 0 | null | null | null | package com.cooksys.ftd.assignments.collections.hierarchy;
import java.util.HashMap;
import java.util.HashSet;
public class DoubleGen {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
| UTF-8 | Java | 235 | java | DoubleGen.java | Java | []
| null | []
| package com.cooksys.ftd.assignments.collections.hierarchy;
import java.util.HashMap;
import java.util.HashSet;
public class DoubleGen {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
| 235 | 0.723404 | 0.723404 | 17 | 12.823529 | 17.800316 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.764706 | false | false | 15 |
0563da3de444b8a1abb57073603e084ff2aee109 | 31,722,628,475,415 | 327c773734638dc62779b7a36e61d94b458ef2a4 | /JAVA AVANZADO/05. Manejo de cadenas en Java/01. Convertir a cadena en Java/src/ensayo2/Ensayo2.java | 9ca57793d0d7299f453b2ee868267cce777848b7 | []
| no_license | LuissMontoya/JavaCourse | https://github.com/LuissMontoya/JavaCourse | dfe852677185714257d3a550134857df2c643685 | c1becfeb0cc50aa31f05171406ebfbc2fd399e98 | refs/heads/master | 2021-01-18T18:34:30.455000 | 2017-02-27T22:07:30 | 2017-02-27T22:07:30 | 86,863,588 | 3 | 0 | null | true | 2017-03-31T22:01:08 | 2017-03-31T22:01:08 | 2017-02-27T22:08:39 | 2017-02-27T22:08:35 | 16,513 | 0 | 0 | 0 | null | null | null | package ensayo2;
public class Ensayo2 {
public static void main(String[] args) {
int numero=10;
String cadena= String.valueOf(numero);//se obtiene el valor de un numero en una cadena
float flotante=10.50f;
String cadenaf=String.valueOf(flotante);
double doble=10.8d;
String cadenad=String.valueOf(doble);
long largo =10000000;
String cadenal=String.valueOf(largo);
boolean booleano=true;
String cadenab=String.valueOf(booleano);
System.out.println(cadena);
System.out.println(cadenaf);
System.out.println(cadenad);
System.out.println(cadenal);
System.out.println(cadenab);
}
}
| UTF-8 | Java | 756 | java | Ensayo2.java | Java | []
| null | []
| package ensayo2;
public class Ensayo2 {
public static void main(String[] args) {
int numero=10;
String cadena= String.valueOf(numero);//se obtiene el valor de un numero en una cadena
float flotante=10.50f;
String cadenaf=String.valueOf(flotante);
double doble=10.8d;
String cadenad=String.valueOf(doble);
long largo =10000000;
String cadenal=String.valueOf(largo);
boolean booleano=true;
String cadenab=String.valueOf(booleano);
System.out.println(cadena);
System.out.println(cadenaf);
System.out.println(cadenad);
System.out.println(cadenal);
System.out.println(cadenab);
}
}
| 756 | 0.600529 | 0.575397 | 26 | 28.076923 | 20.08429 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.615385 | false | false | 15 |
1df75097b7a744787bf3fb530715b94997b81145 | 31,722,628,475,885 | 99ce47ac986abe53937f21a98d2c0063a94d66c1 | /e-Junit/src/main/java/org/ehais/model/iwshop/ProductsInfoEntity.java | dac42af467d9bdeb3117dccb29825a1f548d4f79 | []
| no_license | lgj628/ehais | https://github.com/lgj628/ehais | e8bd5a5bd97577d37dc7b2535829dce6a2171827 | 4a080c96734bde907e1f74c729780490b948a9eb | refs/heads/master | 2018-09-09T23:58:44.999000 | 2018-09-08T03:39:04 | 2018-09-08T03:39:04 | 42,165,960 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.ehais.model.iwshop;
import java.util.List;
public class ProductsInfoEntity {
private ProductsInfoWithBLOBs productInfo;
private List<ProductImages> listProductImages;
public ProductsInfoWithBLOBs getProductInfo() {
return productInfo;
}
public void setProductInfo(ProductsInfoWithBLOBs productInfo) {
this.productInfo = productInfo;
}
public List<ProductImages> getListProductImages() {
return listProductImages;
}
public void setListProductImages(List<ProductImages> listProductImages) {
this.listProductImages = listProductImages;
}
}
| UTF-8 | Java | 608 | java | ProductsInfoEntity.java | Java | []
| null | []
| package org.ehais.model.iwshop;
import java.util.List;
public class ProductsInfoEntity {
private ProductsInfoWithBLOBs productInfo;
private List<ProductImages> listProductImages;
public ProductsInfoWithBLOBs getProductInfo() {
return productInfo;
}
public void setProductInfo(ProductsInfoWithBLOBs productInfo) {
this.productInfo = productInfo;
}
public List<ProductImages> getListProductImages() {
return listProductImages;
}
public void setListProductImages(List<ProductImages> listProductImages) {
this.listProductImages = listProductImages;
}
}
| 608 | 0.758224 | 0.758224 | 28 | 19.714285 | 22.829895 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.035714 | false | false | 15 |
784a13bd8b60101f11263192b3491614c6ad9a59 | 10,101,763,102,879 | ebba21325a75775d28bd46f0474150bd31e17523 | /src/main/java/club/vann/moods/base/BaseDao.java | e750732196e66ef14ef6bc6ae07443037c714c7b | []
| no_license | He1senber9/moods | https://github.com/He1senber9/moods | 7fbcbd867165ae6c19c65832c8304d77d0bd3613 | 13c82a8616781c4a5a895e6ed94e6f2f98148067 | refs/heads/master | 2021-08-27T22:11:23.838000 | 2017-12-10T13:50:15 | 2017-12-10T13:50:15 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* Copyright (C), 2015-2017
* FileName: BaseDao
* Author: fanyun
* Date: 2017/12/7 20:16
* Description:
*/
package club.vann.moods.base;
import club.vann.springframework.db.DruidDataPool;
import java.sql.Connection;
import java.sql.SQLException;
/**
*
*
* @author fanyun
* @create 2017/12/7
* @since 1.0.0
*/
public class BaseDao {
public Connection getConnection() throws SQLException {
return DruidDataPool.getConnection();
}
}
| UTF-8 | Java | 471 | java | BaseDao.java | Java | [
{
"context": "t (C), 2015-2017\n * FileName: BaseDao\n * Author: fanyun\n * Date: 2017/12/7 20:16\n * Description:\n */\n",
"end": 72,
"score": 0.9989188313484192,
"start": 66,
"tag": "USERNAME",
"value": "fanyun"
},
{
"context": "mport java.sql.SQLException;\n\n/**\n *\n *\n * @author fanyun\n * @create 2017/12/7\n * @since 1.0.0\n */\npublic c",
"end": 291,
"score": 0.999511182308197,
"start": 285,
"tag": "USERNAME",
"value": "fanyun"
}
]
| null | []
| /**
* Copyright (C), 2015-2017
* FileName: BaseDao
* Author: fanyun
* Date: 2017/12/7 20:16
* Description:
*/
package club.vann.moods.base;
import club.vann.springframework.db.DruidDataPool;
import java.sql.Connection;
import java.sql.SQLException;
/**
*
*
* @author fanyun
* @create 2017/12/7
* @since 1.0.0
*/
public class BaseDao {
public Connection getConnection() throws SQLException {
return DruidDataPool.getConnection();
}
}
| 471 | 0.673036 | 0.611465 | 27 | 16.444445 | 16.196327 | 59 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.222222 | false | false | 15 |
a43be66aa6e1a49705165d749ffd6a33c78cd726 | 10,608,569,225,753 | a9b48b059e7ae01947d6e5deffc50edc38182335 | /FestFinder/src/com/de/client/view/MenuView.java | 290fb972357f25d42870472741ab3ffe902bde9f | []
| no_license | JohannaSchmidt/FestivalFinder | https://github.com/JohannaSchmidt/FestivalFinder | cc933c638089468e4f20b290809141c2c27bae40 | a6e338dc1ab65e7bf7132c50e6f5d76e29edd958 | refs/heads/master | 2020-06-03T07:54:40.802000 | 2014-07-06T18:16:17 | 2014-07-06T18:16:17 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.de.client.view;
import com.de.client.presenter.MenuPresenter;
import com.de.shared.User;
import com.google.gwt.dom.client.Style.Cursor;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.PushButton;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
public class MenuView extends Composite implements MenuPresenter.Display{
private Label lblSuche;
private TextBox bandSuche;
private Button suchen;
private PushButton home;
private PushButton festivals;
private PushButton bands;
private ListBox suche;
private PushButton addFestival;
private PushButton addBand;
private PushButton deleteFestival;
private PushButton deleteBand;
public MenuView(User user){
FlowPanel vPanel = new FlowPanel();
FlowPanel suchPanel = new FlowPanel();
initWidget(vPanel);
vPanel.setStyleName("suche");
suchPanel.setStyleName("suchpanel");
lblSuche = new Label("Suchen nach:");
lblSuche.setStyleName("suchentext");
suche = new ListBox();
suche.addItem("Band");
suche.addItem("Festival");
suche.addItem("Genre");
suche.setStyleName("suchenfeld");
suche.getElement().getStyle().setCursor(Cursor.POINTER);
bandSuche = new TextBox();
bandSuche.setText("Suchbegriff eingeben");
bandSuche.setStyleName("eingabeFeld");
suchen = new Button("Suchen");
suchen.setStyleName("suchenbutton");
suchen.getElement().getStyle().setCursor(Cursor.POINTER);
addFestival = new PushButton(new Image("images/Festivalanlegen.png"));
addBand = new PushButton(new Image("images/Bandanlegen.png"));
deleteFestival = new PushButton(new Image("images/Festivalloeschen.png"));
deleteBand = new PushButton(new Image("images/Bandloeschen.png"));
home = new PushButton(new Image("images/Home.png"));
home.setStyleName("buttons");
home.getElement().getStyle().setCursor(Cursor.POINTER);
festivals = new PushButton(new Image("images/Festivals.png"));
festivals.setStyleName("buttons");
festivals.getElement().getStyle().setCursor(Cursor.POINTER);
bands = new PushButton(new Image("images/Bands.png"));
bands.setStyleName("buttons");
bands.getElement().getStyle().setCursor(Cursor.POINTER);
suchPanel.add(lblSuche);
suchPanel.add(bandSuche);
suchPanel.add(suche);
suchPanel.add(suchen);
vPanel.add(suchPanel);
vPanel.add(home);
vPanel.add(festivals);
vPanel.add(bands);
if(user != null){
if(user.getRolle().equals("Admin")){
addFestival.setStyleName("buttons");
addFestival.getElement().getStyle().setCursor(Cursor.POINTER);
addBand.setStyleName("buttons");
addBand.getElement().getStyle().setCursor(Cursor.POINTER);
deleteFestival.setStyleName("buttons");
deleteFestival.getElement().getStyle().setCursor(Cursor.POINTER);
deleteBand.setStyleName("buttons");
deleteBand.getElement().getStyle().setCursor(Cursor.POINTER);
vPanel.add(addBand);
vPanel.add(deleteBand);
vPanel.add(addFestival);
vPanel.add(deleteFestival);
}
}
}
public String getDropDown(){
return suche.getItemText(suche.getSelectedIndex());
}
public HasClickHandlers getSuchenButton() {
return suchen;
}
public HasClickHandlers getAddFestivalButton() {
return addFestival;
}
public HasClickHandlers getAddBandButton() {
return addBand;
}
public HasClickHandlers getDeleteFestivalButton() {
return deleteFestival;
}
public HasClickHandlers getDeleteBandButton() {
return deleteBand;
}
public HasClickHandlers getFestivalsButton() {
return festivals;
}
public HasClickHandlers getHomeButton(){
return home;
}
public TextBox getSucheBox(){
return bandSuche;
}
public HasClickHandlers getBandButton() {
return bands;
}
public String getName() {
return bandSuche.getText();
}
public Widget asWidget(){
return this;
}
} | UTF-8 | Java | 4,457 | java | MenuView.java | Java | []
| null | []
| package com.de.client.view;
import com.de.client.presenter.MenuPresenter;
import com.de.shared.User;
import com.google.gwt.dom.client.Style.Cursor;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.PushButton;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
public class MenuView extends Composite implements MenuPresenter.Display{
private Label lblSuche;
private TextBox bandSuche;
private Button suchen;
private PushButton home;
private PushButton festivals;
private PushButton bands;
private ListBox suche;
private PushButton addFestival;
private PushButton addBand;
private PushButton deleteFestival;
private PushButton deleteBand;
public MenuView(User user){
FlowPanel vPanel = new FlowPanel();
FlowPanel suchPanel = new FlowPanel();
initWidget(vPanel);
vPanel.setStyleName("suche");
suchPanel.setStyleName("suchpanel");
lblSuche = new Label("Suchen nach:");
lblSuche.setStyleName("suchentext");
suche = new ListBox();
suche.addItem("Band");
suche.addItem("Festival");
suche.addItem("Genre");
suche.setStyleName("suchenfeld");
suche.getElement().getStyle().setCursor(Cursor.POINTER);
bandSuche = new TextBox();
bandSuche.setText("Suchbegriff eingeben");
bandSuche.setStyleName("eingabeFeld");
suchen = new Button("Suchen");
suchen.setStyleName("suchenbutton");
suchen.getElement().getStyle().setCursor(Cursor.POINTER);
addFestival = new PushButton(new Image("images/Festivalanlegen.png"));
addBand = new PushButton(new Image("images/Bandanlegen.png"));
deleteFestival = new PushButton(new Image("images/Festivalloeschen.png"));
deleteBand = new PushButton(new Image("images/Bandloeschen.png"));
home = new PushButton(new Image("images/Home.png"));
home.setStyleName("buttons");
home.getElement().getStyle().setCursor(Cursor.POINTER);
festivals = new PushButton(new Image("images/Festivals.png"));
festivals.setStyleName("buttons");
festivals.getElement().getStyle().setCursor(Cursor.POINTER);
bands = new PushButton(new Image("images/Bands.png"));
bands.setStyleName("buttons");
bands.getElement().getStyle().setCursor(Cursor.POINTER);
suchPanel.add(lblSuche);
suchPanel.add(bandSuche);
suchPanel.add(suche);
suchPanel.add(suchen);
vPanel.add(suchPanel);
vPanel.add(home);
vPanel.add(festivals);
vPanel.add(bands);
if(user != null){
if(user.getRolle().equals("Admin")){
addFestival.setStyleName("buttons");
addFestival.getElement().getStyle().setCursor(Cursor.POINTER);
addBand.setStyleName("buttons");
addBand.getElement().getStyle().setCursor(Cursor.POINTER);
deleteFestival.setStyleName("buttons");
deleteFestival.getElement().getStyle().setCursor(Cursor.POINTER);
deleteBand.setStyleName("buttons");
deleteBand.getElement().getStyle().setCursor(Cursor.POINTER);
vPanel.add(addBand);
vPanel.add(deleteBand);
vPanel.add(addFestival);
vPanel.add(deleteFestival);
}
}
}
public String getDropDown(){
return suche.getItemText(suche.getSelectedIndex());
}
public HasClickHandlers getSuchenButton() {
return suchen;
}
public HasClickHandlers getAddFestivalButton() {
return addFestival;
}
public HasClickHandlers getAddBandButton() {
return addBand;
}
public HasClickHandlers getDeleteFestivalButton() {
return deleteFestival;
}
public HasClickHandlers getDeleteBandButton() {
return deleteBand;
}
public HasClickHandlers getFestivalsButton() {
return festivals;
}
public HasClickHandlers getHomeButton(){
return home;
}
public TextBox getSucheBox(){
return bandSuche;
}
public HasClickHandlers getBandButton() {
return bands;
}
public String getName() {
return bandSuche.getText();
}
public Widget asWidget(){
return this;
}
} | 4,457 | 0.710792 | 0.710792 | 159 | 26.044025 | 21.012829 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.119497 | false | false | 15 |
cf30ed604b67a9cf92cd8822d8cf273e2439c870 | 4,209,067,972,930 | 6022a8314660efd8838975aa8c6413b08cecf829 | /FeiPhoneInfo/src/com/njnu/kai/feiphoneinfo/DetailTaskActivity.java | 7f831d40445ecf7928d83641b9171a3ced0e984c | []
| no_license | qianhk/FeiAndroid | https://github.com/qianhk/FeiAndroid | 504c9fa457d9ca48171313ca9a330b96d514817a | 82d4806114b1d8cea74ce136371938270f1d495e | refs/heads/master | 2023-08-03T04:33:57.848000 | 2023-07-21T15:21:18 | 2023-07-21T15:21:18 | 3,962,814 | 3 | 4 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.njnu.kai.feiphoneinfo;
import java.lang.reflect.Method;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class DetailTaskActivity extends Activity {
DetailProgramUtil detailInfo = null;
@Override
public void onCreate(Bundle savedInstanceState) {
// public void OnCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.task_detail);
Intent intent = getIntent();
detailInfo = (DetailProgramUtil) intent.getSerializableExtra("detailData");
Log.v("DetailTaskActivity", "detailInfo=" + detailInfo);
TextView tv = null;
tv = (TextView) findViewById(R.id.detail_process_name);
if (detailInfo == null) {
tv.setText("no infomation.");
return;
}
tv.setText(detailInfo.getProcessName());
tv = (TextView) findViewById(R.id.detail_process_copyright);
tv.setText(detailInfo.getCompanyName());
tv = (TextView) findViewById(R.id.detail_process_install_dir);
tv.setText(detailInfo.getSourceDir());
tv = (TextView) findViewById(R.id.detail_process_data_dir);
tv.setText(detailInfo.getDataDir());
tv = (TextView) findViewById(R.id.detail_process_package_size);
tv.setText(detailInfo.getPackageSize());
tv = (TextView) findViewById(R.id.detail_process_permission);
tv.setText(detailInfo.getUserPermissions());
tv = (TextView) findViewById(R.id.detail_process_service);
tv.setText(detailInfo.getServices());
tv = (TextView) findViewById(R.id.detail_process_activity);
tv.setText(detailInfo.getActivities());
Button btnKillProcess = (Button) findViewById(R.id.btn_kill_process);
btnKillProcess.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
if (detailInfo.getProcessName().equals("com.njnu.kai.feiphoneinfo")) {
returnToHome();
// android.os.Process.killProcess(android.os.Process.myPid());
// System.exit(0);
} else {
try {
Method ms = activityManager.getClass().getDeclaredMethod("killBackgroundProcesses", String.class);
ms.invoke(activityManager, detailInfo.getProcessName());
}
catch (Exception e) {
Log.v("DetailTaskActivity", "No method killBackgroundProcesses");
activityManager.restartPackage(detailInfo.getProcessName());
}
// activityManager.killBackgroundProcesses(detailInfo.getProcessName());
}
}
});
}
private void returnToHome() {
Intent home = new Intent(Intent.ACTION_MAIN);
home.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
home.addCategory(Intent.CATEGORY_HOME);
startActivity(home);
}
// 结束其他程序
// ActivityManager.killBackgroundProcesses(PackageName)
}
| UTF-8 | Java | 2,953 | java | DetailTaskActivity.java | Java | []
| null | []
| package com.njnu.kai.feiphoneinfo;
import java.lang.reflect.Method;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class DetailTaskActivity extends Activity {
DetailProgramUtil detailInfo = null;
@Override
public void onCreate(Bundle savedInstanceState) {
// public void OnCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.task_detail);
Intent intent = getIntent();
detailInfo = (DetailProgramUtil) intent.getSerializableExtra("detailData");
Log.v("DetailTaskActivity", "detailInfo=" + detailInfo);
TextView tv = null;
tv = (TextView) findViewById(R.id.detail_process_name);
if (detailInfo == null) {
tv.setText("no infomation.");
return;
}
tv.setText(detailInfo.getProcessName());
tv = (TextView) findViewById(R.id.detail_process_copyright);
tv.setText(detailInfo.getCompanyName());
tv = (TextView) findViewById(R.id.detail_process_install_dir);
tv.setText(detailInfo.getSourceDir());
tv = (TextView) findViewById(R.id.detail_process_data_dir);
tv.setText(detailInfo.getDataDir());
tv = (TextView) findViewById(R.id.detail_process_package_size);
tv.setText(detailInfo.getPackageSize());
tv = (TextView) findViewById(R.id.detail_process_permission);
tv.setText(detailInfo.getUserPermissions());
tv = (TextView) findViewById(R.id.detail_process_service);
tv.setText(detailInfo.getServices());
tv = (TextView) findViewById(R.id.detail_process_activity);
tv.setText(detailInfo.getActivities());
Button btnKillProcess = (Button) findViewById(R.id.btn_kill_process);
btnKillProcess.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
if (detailInfo.getProcessName().equals("com.njnu.kai.feiphoneinfo")) {
returnToHome();
// android.os.Process.killProcess(android.os.Process.myPid());
// System.exit(0);
} else {
try {
Method ms = activityManager.getClass().getDeclaredMethod("killBackgroundProcesses", String.class);
ms.invoke(activityManager, detailInfo.getProcessName());
}
catch (Exception e) {
Log.v("DetailTaskActivity", "No method killBackgroundProcesses");
activityManager.restartPackage(detailInfo.getProcessName());
}
// activityManager.killBackgroundProcesses(detailInfo.getProcessName());
}
}
});
}
private void returnToHome() {
Intent home = new Intent(Intent.ACTION_MAIN);
home.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
home.addCategory(Intent.CATEGORY_HOME);
startActivity(home);
}
// 结束其他程序
// ActivityManager.killBackgroundProcesses(PackageName)
}
| 2,953 | 0.742265 | 0.741925 | 90 | 31.677778 | 25.676546 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.466667 | false | false | 15 |
bff378d884e80abb919613fc0c9c15c1995a4e3d | 4,209,067,972,668 | 1278fc14e3f254f9e102ff6811a9d3fb7a70dc85 | /src/main/java/org/normal/framework/controller/UserRoleController.java | 9a2c51fe85869ec85c338d2f603d5204df2b5cf3 | [
"MIT"
]
| permissive | jianjustin/normal-initialize-project | https://github.com/jianjustin/normal-initialize-project | 5a4c913afb601cbea4f8cf3be8689176e4076be5 | e276c9b223bc01b83cfba67381c727f5d702600f | refs/heads/master | 2020-03-07T03:39:33.666000 | 2019-11-07T09:23:58 | 2019-11-07T09:23:58 | 127,242,805 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.normal.framework.controller;
import org.normal.framework.domain.UserRole;
import org.normal.framework.service.UserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api")
public class UserRoleController {
@Autowired
public UserRoleService userRoleService;
@GetMapping("/userRoles")
@PreAuthorize("hasAuthority('UserRole.getAllUserRoles')")
public List<UserRole> getAllUserRoles() {
return userRoleService.getAllUserRoles();
}
@GetMapping("/userRoles/{id}")
@PreAuthorize("hasAuthority('UserRole.getUserRole')")
public UserRole getUserRole(@PathVariable("id") long id) {
return userRoleService.getUserRoleById(id);
}
@DeleteMapping("/userRoles/{id}")
@PreAuthorize("hasAuthority('UserRole.deleteUserRoles')")
public void deleteUserRoles(@PathVariable("id") long id) {
userRoleService.delete(id);
}
@PostMapping("/userRoles")
@PreAuthorize("hasAuthority('UserRole.saveUserRoles')")
public long saveUserRoles(@RequestBody UserRole userRole) {
userRoleService.saveOrUpdate(userRole);
return userRole.id;
}
}
| UTF-8 | Java | 1,332 | java | UserRoleController.java | Java | []
| null | []
| package org.normal.framework.controller;
import org.normal.framework.domain.UserRole;
import org.normal.framework.service.UserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api")
public class UserRoleController {
@Autowired
public UserRoleService userRoleService;
@GetMapping("/userRoles")
@PreAuthorize("hasAuthority('UserRole.getAllUserRoles')")
public List<UserRole> getAllUserRoles() {
return userRoleService.getAllUserRoles();
}
@GetMapping("/userRoles/{id}")
@PreAuthorize("hasAuthority('UserRole.getUserRole')")
public UserRole getUserRole(@PathVariable("id") long id) {
return userRoleService.getUserRoleById(id);
}
@DeleteMapping("/userRoles/{id}")
@PreAuthorize("hasAuthority('UserRole.deleteUserRoles')")
public void deleteUserRoles(@PathVariable("id") long id) {
userRoleService.delete(id);
}
@PostMapping("/userRoles")
@PreAuthorize("hasAuthority('UserRole.saveUserRoles')")
public long saveUserRoles(@RequestBody UserRole userRole) {
userRoleService.saveOrUpdate(userRole);
return userRole.id;
}
}
| 1,332 | 0.737237 | 0.737237 | 41 | 31.487804 | 22.999599 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.317073 | false | false | 15 |
8aec2fa75b8b191586776638f2a24288f9ada380 | 14,164,802,163,685 | ade44836a4d06eeb4529217c3d8a99a829e66bb2 | /src/main/java/edu/neu/cs5200/dao/PersonDao.java | 9c972399e0192476fb351048920b36d4abcf9f49 | []
| no_license | DanielZhangLing/cs5200-summer2018-zhang | https://github.com/DanielZhangLing/cs5200-summer2018-zhang | 226f54cf7013d2738f679dcc0b8049f05abcf0d9 | 8d2df367a570ed42ed85bb784987b2b19652ede9 | refs/heads/master | 2020-03-18T00:45:45.877000 | 2018-08-07T18:57:17 | 2018-08-07T18:57:17 | 134,111,369 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package edu.neu.cs5200.dao;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import edu.neu.cs5200.models.Person;
public class PersonDao extends BaseDao {
private static PersonDao instance = null;
private PersonDao() {
}
public static PersonDao getInstance() {
if (instance == null)
instance = new PersonDao();
return instance;
}
final String CREATE_PERSON = "INSERT INTO hw3_zhang_ling_summer_2018.Person (firstName, lastName, username, password, email, dob) VALUES(?, ?, ?, ?, ?, ?);";
final String FIND_PERSON_BY_ID = "SELECT * FROM hw3_zhang_ling_summer_2018.Person WHERE id = ?;";
final String FIND_PERSON_BY_USERNAME = "SELECT * FROM hw3_zhang_ling_summer_2018.Person WHERE username = ?;";
final String FIND_PERSON_BY_CREDENTIALS = "SELECT * FROM hw3_zhang_ling_summer_2018.Person WHERE username = ? AND password = ?;";
final String UPDATE_PERSON = "UPDATE hw3_zhang_ling_summer_2018.Person SET firstName = ?, lastName = ?, username = ?, password = ?, email = ?, dob = ? WHERE id = ?;";
final String DELETE_PERSON = "DELETE FROM hw3_zhang_ling_summer_2018.Person WHERE id = ?;";
public int createPerson(Person person) {
int personId = -1;
try {
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection(DB_URL, USER, PASS);
pstmt = conn.prepareStatement(CREATE_PERSON, Statement.RETURN_GENERATED_KEYS);
pstmt.setString(1, person.getFirstName());
pstmt.setString(2, person.getLastName());
pstmt.setString(3, person.getUsername());
pstmt.setString(4, person.getPassword());
pstmt.setString(5, person.getEmail());
pstmt.setDate(6, person.getDob());
pstmt.executeUpdate();
ResultSet rs = pstmt.getGeneratedKeys();
if (rs.next())
personId = rs.getInt(1);
} catch (SQLException se) {
se.printStackTrace(); // handle errors for JDBC
} catch (Exception e) {
e.printStackTrace(); // handle Class.forName
} finally {
try {
if (conn != null)
conn.close();
} catch (SQLException se2) { // ignore, can't help it
}
}
return personId;
}
public Person findPersonById(int id) {
Person person = null;
try {
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection(DB_URL, USER, PASS);
pstmt = conn.prepareStatement(FIND_PERSON_BY_ID);
pstmt.setInt(1, id);
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
String firstName = rs.getString("firstName");
String lastName = rs.getString("lastName");
String password = rs.getString("password");
String username = rs.getString("username");
String email = rs.getString("password");
Date dob = rs.getDate("dob");
person = new Person(id, firstName, lastName, username, password, email, dob);
}
} catch (SQLException se) {
se.printStackTrace(); // handle errors for JDBC
} catch (Exception e) {
e.printStackTrace(); // handle Class.forName
} finally {
try {
if (conn != null)
conn.close();
} catch (SQLException se2) { // ignore, can't help it
}
}
return person;
}
public Person findPersonByUsername(String username) {
Person person = null;
try {
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection(DB_URL, USER, PASS);
pstmt = conn.prepareStatement(FIND_PERSON_BY_USERNAME);
pstmt.setString(1, username);
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
int id = rs.getInt("id");
String firstName = rs.getString("firstName");
String lastName = rs.getString("lastName");
String password = rs.getString("password");
String email = rs.getString("password");
Date dob = rs.getDate("dob");
person = new Person(id, firstName, lastName, username, password, email, dob);
}
} catch (SQLException se) {
se.printStackTrace(); // handle errors for JDBC
} catch (Exception e) {
e.printStackTrace(); // handle Class.forName
} finally {
try {
if (conn != null)
conn.close();
} catch (SQLException se2) { // ignore, can't help it
}
}
return person;
}
public Person findPersonByCredentials(String username, String password) {
Person person = null;
try {
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection(DB_URL, USER, PASS);
pstmt = conn.prepareStatement(FIND_PERSON_BY_CREDENTIALS);
pstmt.setString(1, username);
pstmt.setString(2, password);
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
int id = rs.getInt("id");
String firstName = rs.getString("firstName");
String lastName = rs.getString("lastName");
String email = rs.getString("password");
Date dob = rs.getDate("dob");
person = new Person(id, firstName, lastName, username, password, email, dob);
}
} catch (SQLException se) {
se.printStackTrace(); // handle errors for JDBC
} catch (Exception e) {
e.printStackTrace(); // handle Class.forName
} finally {
try {
if (conn != null)
conn.close();
} catch (SQLException se2) { // ignore, can't help it
}
}
return person;
}
public int updatePerson(int personId, Person person) {
int result = 0;
try {
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection(DB_URL, USER, PASS);
pstmt = conn.prepareStatement(UPDATE_PERSON);
pstmt.setString(1, person.getFirstName());
pstmt.setString(2, person.getLastName());
pstmt.setString(3, person.getUsername());
pstmt.setString(4, person.getPassword());
pstmt.setString(5, person.getEmail());
pstmt.setDate(6, person.getDob());
pstmt.setInt(7, personId);
result = pstmt.executeUpdate();
} catch (SQLException se) {
se.printStackTrace(); // handle errors for JDBC
} catch (Exception e) {
e.printStackTrace(); // handle Class.forName
} finally {
try {
if (conn != null)
conn.close();
} catch (SQLException se2) { // ignore, can't help it
}
}
return result;
}
public int deletePerson(int personId) {
int result = 0;
try {
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection(DB_URL, USER, PASS);
pstmt = conn.prepareStatement(DELETE_PERSON);
pstmt.setInt(1, personId);
result = pstmt.executeUpdate();
} catch (SQLException se) {
se.printStackTrace(); // handle errors for JDBC
} catch (Exception e) {
e.printStackTrace(); // handle Class.forName
} finally {
try {
if (conn != null)
conn.close();
} catch (SQLException se2) { // ignore, can't help it
}
}
return result;
}
}
| UTF-8 | Java | 6,489 | java | PersonDao.java | Java | [
{
"context": " = rs.getString(\"lastName\");\n\t\t\t\tString password = rs.getString(\"password\");\n\t\t\t\tString username = rs.getString(\"",
"end": 2558,
"score": 0.992011547088623,
"start": 2546,
"tag": "PASSWORD",
"value": "rs.getString"
},
{
"context": "(\"lastName\");\n\t\t\t\tString password = rs.getString(\"password\");\n\t\t\t\tString username = rs.getString(\"username\")",
"end": 2568,
"score": 0.9922154545783997,
"start": 2560,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "(\"password\");\n\t\t\t\tString username = rs.getString(\"username\");\n\t\t\t\tString email = rs.getString(\"password\");\n\t",
"end": 2616,
"score": 0.9988892078399658,
"start": 2608,
"tag": "USERNAME",
"value": "username"
}
]
| null | []
| package edu.neu.cs5200.dao;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import edu.neu.cs5200.models.Person;
public class PersonDao extends BaseDao {
private static PersonDao instance = null;
private PersonDao() {
}
public static PersonDao getInstance() {
if (instance == null)
instance = new PersonDao();
return instance;
}
final String CREATE_PERSON = "INSERT INTO hw3_zhang_ling_summer_2018.Person (firstName, lastName, username, password, email, dob) VALUES(?, ?, ?, ?, ?, ?);";
final String FIND_PERSON_BY_ID = "SELECT * FROM hw3_zhang_ling_summer_2018.Person WHERE id = ?;";
final String FIND_PERSON_BY_USERNAME = "SELECT * FROM hw3_zhang_ling_summer_2018.Person WHERE username = ?;";
final String FIND_PERSON_BY_CREDENTIALS = "SELECT * FROM hw3_zhang_ling_summer_2018.Person WHERE username = ? AND password = ?;";
final String UPDATE_PERSON = "UPDATE hw3_zhang_ling_summer_2018.Person SET firstName = ?, lastName = ?, username = ?, password = ?, email = ?, dob = ? WHERE id = ?;";
final String DELETE_PERSON = "DELETE FROM hw3_zhang_ling_summer_2018.Person WHERE id = ?;";
public int createPerson(Person person) {
int personId = -1;
try {
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection(DB_URL, USER, PASS);
pstmt = conn.prepareStatement(CREATE_PERSON, Statement.RETURN_GENERATED_KEYS);
pstmt.setString(1, person.getFirstName());
pstmt.setString(2, person.getLastName());
pstmt.setString(3, person.getUsername());
pstmt.setString(4, person.getPassword());
pstmt.setString(5, person.getEmail());
pstmt.setDate(6, person.getDob());
pstmt.executeUpdate();
ResultSet rs = pstmt.getGeneratedKeys();
if (rs.next())
personId = rs.getInt(1);
} catch (SQLException se) {
se.printStackTrace(); // handle errors for JDBC
} catch (Exception e) {
e.printStackTrace(); // handle Class.forName
} finally {
try {
if (conn != null)
conn.close();
} catch (SQLException se2) { // ignore, can't help it
}
}
return personId;
}
public Person findPersonById(int id) {
Person person = null;
try {
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection(DB_URL, USER, PASS);
pstmt = conn.prepareStatement(FIND_PERSON_BY_ID);
pstmt.setInt(1, id);
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
String firstName = rs.getString("firstName");
String lastName = rs.getString("lastName");
String password = <PASSWORD>("<PASSWORD>");
String username = rs.getString("username");
String email = rs.getString("password");
Date dob = rs.getDate("dob");
person = new Person(id, firstName, lastName, username, password, email, dob);
}
} catch (SQLException se) {
se.printStackTrace(); // handle errors for JDBC
} catch (Exception e) {
e.printStackTrace(); // handle Class.forName
} finally {
try {
if (conn != null)
conn.close();
} catch (SQLException se2) { // ignore, can't help it
}
}
return person;
}
public Person findPersonByUsername(String username) {
Person person = null;
try {
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection(DB_URL, USER, PASS);
pstmt = conn.prepareStatement(FIND_PERSON_BY_USERNAME);
pstmt.setString(1, username);
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
int id = rs.getInt("id");
String firstName = rs.getString("firstName");
String lastName = rs.getString("lastName");
String password = rs.getString("password");
String email = rs.getString("password");
Date dob = rs.getDate("dob");
person = new Person(id, firstName, lastName, username, password, email, dob);
}
} catch (SQLException se) {
se.printStackTrace(); // handle errors for JDBC
} catch (Exception e) {
e.printStackTrace(); // handle Class.forName
} finally {
try {
if (conn != null)
conn.close();
} catch (SQLException se2) { // ignore, can't help it
}
}
return person;
}
public Person findPersonByCredentials(String username, String password) {
Person person = null;
try {
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection(DB_URL, USER, PASS);
pstmt = conn.prepareStatement(FIND_PERSON_BY_CREDENTIALS);
pstmt.setString(1, username);
pstmt.setString(2, password);
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
int id = rs.getInt("id");
String firstName = rs.getString("firstName");
String lastName = rs.getString("lastName");
String email = rs.getString("password");
Date dob = rs.getDate("dob");
person = new Person(id, firstName, lastName, username, password, email, dob);
}
} catch (SQLException se) {
se.printStackTrace(); // handle errors for JDBC
} catch (Exception e) {
e.printStackTrace(); // handle Class.forName
} finally {
try {
if (conn != null)
conn.close();
} catch (SQLException se2) { // ignore, can't help it
}
}
return person;
}
public int updatePerson(int personId, Person person) {
int result = 0;
try {
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection(DB_URL, USER, PASS);
pstmt = conn.prepareStatement(UPDATE_PERSON);
pstmt.setString(1, person.getFirstName());
pstmt.setString(2, person.getLastName());
pstmt.setString(3, person.getUsername());
pstmt.setString(4, person.getPassword());
pstmt.setString(5, person.getEmail());
pstmt.setDate(6, person.getDob());
pstmt.setInt(7, personId);
result = pstmt.executeUpdate();
} catch (SQLException se) {
se.printStackTrace(); // handle errors for JDBC
} catch (Exception e) {
e.printStackTrace(); // handle Class.forName
} finally {
try {
if (conn != null)
conn.close();
} catch (SQLException se2) { // ignore, can't help it
}
}
return result;
}
public int deletePerson(int personId) {
int result = 0;
try {
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection(DB_URL, USER, PASS);
pstmt = conn.prepareStatement(DELETE_PERSON);
pstmt.setInt(1, personId);
result = pstmt.executeUpdate();
} catch (SQLException se) {
se.printStackTrace(); // handle errors for JDBC
} catch (Exception e) {
e.printStackTrace(); // handle Class.forName
} finally {
try {
if (conn != null)
conn.close();
} catch (SQLException se2) { // ignore, can't help it
}
}
return result;
}
}
| 6,489 | 0.667283 | 0.657112 | 206 | 30.5 | 26.05162 | 167 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.300971 | false | false | 15 |
0c3a9a9aa4537d1877fdb465c6d18d394ba107fa | 21,337,397,545,706 | b19dcd301f4b266ebff0854dc142fc16653d4e6f | /java/Thmod/Cards/ItemCards/AbstractItemCards.java | e47562c52d9a20a5ea0cc6c9f763009c647c3252 | []
| no_license | HOYKJ/KomeijiMod | https://github.com/HOYKJ/KomeijiMod | fea7021ef13c4532001f4378635f67b3e84c8afc | 760e0c51b918e406ba659a9c8b173a7354c687f6 | refs/heads/master | 2021-10-29T01:33:45.187000 | 2021-10-21T13:34:21 | 2021-10-21T13:34:21 | 140,571,160 | 11 | 6 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Thmod.Cards.ItemCards;
import com.badlogic.gdx.graphics.Color;
import com.megacrit.cardcrawl.actions.common.ExhaustSpecificCardAction;
import com.megacrit.cardcrawl.cards.AbstractCard;
import com.megacrit.cardcrawl.characters.AbstractPlayer;
import com.megacrit.cardcrawl.core.CardCrawlGame;
import com.megacrit.cardcrawl.dungeons.AbstractDungeon;
import com.megacrit.cardcrawl.localization.CardStrings;
import com.megacrit.cardcrawl.monsters.AbstractMonster;
import Thmod.Patches.AbstractCardEnum;
import Thmod.ThMod;
import basemod.abstracts.CustomCard;
public abstract class AbstractItemCards extends CustomCard {
public AbstractItemCards(final String id, final String name, final int cost, final String description, final AbstractCard.CardType type, final AbstractCard.CardRarity rarity, final AbstractCard.CardTarget target) {
super(id, name, ThMod.itemCardImage(id), cost, description, type, AbstractCardEnum.Item符卡, rarity, target);
this.isEthereal = true;
this.exhaust = true;
this.upgraded = true;
this.glowColor = Color.ORANGE.cpy();
}
public boolean canUpgrade()
{
return false;
}
public void triggerOnManualDiscard(){
AbstractDungeon.actionManager.addToTop(new ExhaustSpecificCardAction(this, AbstractDungeon.player.discardPile));
AbstractDungeon.actionManager.addToTop(new ExhaustSpecificCardAction(this, AbstractDungeon.player.hand));
}
public boolean canUse(AbstractPlayer p, AbstractMonster m){
super.canUse(p,m);
if (p.hasPower("PointPower")) {
if (p.getPower("PointPower").amount >= 1) {
return true;
}
}
this.cantUseMessage = "我没有足够的P点";
return false;
}
}
| UTF-8 | Java | 1,788 | java | AbstractItemCards.java | Java | []
| null | []
| package Thmod.Cards.ItemCards;
import com.badlogic.gdx.graphics.Color;
import com.megacrit.cardcrawl.actions.common.ExhaustSpecificCardAction;
import com.megacrit.cardcrawl.cards.AbstractCard;
import com.megacrit.cardcrawl.characters.AbstractPlayer;
import com.megacrit.cardcrawl.core.CardCrawlGame;
import com.megacrit.cardcrawl.dungeons.AbstractDungeon;
import com.megacrit.cardcrawl.localization.CardStrings;
import com.megacrit.cardcrawl.monsters.AbstractMonster;
import Thmod.Patches.AbstractCardEnum;
import Thmod.ThMod;
import basemod.abstracts.CustomCard;
public abstract class AbstractItemCards extends CustomCard {
public AbstractItemCards(final String id, final String name, final int cost, final String description, final AbstractCard.CardType type, final AbstractCard.CardRarity rarity, final AbstractCard.CardTarget target) {
super(id, name, ThMod.itemCardImage(id), cost, description, type, AbstractCardEnum.Item符卡, rarity, target);
this.isEthereal = true;
this.exhaust = true;
this.upgraded = true;
this.glowColor = Color.ORANGE.cpy();
}
public boolean canUpgrade()
{
return false;
}
public void triggerOnManualDiscard(){
AbstractDungeon.actionManager.addToTop(new ExhaustSpecificCardAction(this, AbstractDungeon.player.discardPile));
AbstractDungeon.actionManager.addToTop(new ExhaustSpecificCardAction(this, AbstractDungeon.player.hand));
}
public boolean canUse(AbstractPlayer p, AbstractMonster m){
super.canUse(p,m);
if (p.hasPower("PointPower")) {
if (p.getPower("PointPower").amount >= 1) {
return true;
}
}
this.cantUseMessage = "我没有足够的P点";
return false;
}
}
| 1,788 | 0.733898 | 0.733333 | 46 | 37.47826 | 40.259884 | 218 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.913043 | false | false | 15 |
2de0cf06be7ad3fb1e649ff14dde43bd0a375757 | 9,354,438,795,046 | 4878e22322c27d022324ce1ae6ee77defd8bff7b | /app/src/main/java/id/t12ue/kalimutu/helpers/Cons.java | c663795a8574941ab30c617b1eaac57df67f9312 | []
| no_license | Barcode36/KalimutuOutdoor | https://github.com/Barcode36/KalimutuOutdoor | 2d61b5585f842010523ee15689c75e1f81105bf8 | 1b2a34c4aaf1ac988f6d3ed77eae28e24594adf4 | refs/heads/master | 2023-07-04T21:23:14.596000 | 2021-08-25T19:22:19 | 2021-08-25T19:22:19 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package id.t12ue.kalimutu.helpers;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Random;
import java.util.TimeZone;
public class Cons {
public static String KEY_USER="USERS";
public static String KEY_TRANSACTION="TRANSACTIONS";
public static String KEY_BANK="BANKS";
public static String KEY_PACKAGE="PACKAGES";
public static String KEY_PRODUCT="PRODUCTS";
public static String KEY_NOTIFICATION="NOTIFICATIONS";
public static String KEY_DETAIL="DETAILS";
public static String KEY_CART="CARTS";
public static String KEY_TOKEN="TOKENS";
public static String KEY_IMAGE="IMAGES";
private static final String ALLOWED_CHARACTERS ="0123456789QWERTYUIOPASDFGHJKLZXCBNM";
public static String status(int sts){
String status = null;
if (sts==-2){
status="Bukti pembayaran invalid";
} else if (sts==-1){
status="Pesanan dibatalkan";
} else if (sts==0){
status="Pesanan sedang disiapkan";
} else if (sts==1){
status="Menunggu verifikasi pemabayaran";
} else if (sts==2){
status="Pembayaran telah diverifikasi";
} else if (sts==3){
status="Pesanan telah diambil";
} else if (sts==4){
status="Pesanan telah dikembalikan";
}
return status;
}
public static String dateFormat(String dt){
String s=null;
if (!dt.equals("-")){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat formatID = new SimpleDateFormat("dd-MMM-yyyy");
TimeZone tz = TimeZone.getTimeZone("Asia/Jakarta");
formatID.setTimeZone(tz);
try {
s = formatID.format(sdf.parse(dt));
} catch (ParseException e) {
e.printStackTrace();
}
} else {
s="-";
}
return s;
}
public static float distFrom(double lat1, double lng1, double lat2, double lng2) {
double earthRadius = 6371000; //meters
double dLat = Math.toRadians(lat2-lat1);
double dLng = Math.toRadians(lng2-lng1);
double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
Math.sin(dLng/2) * Math.sin(dLng/2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
float dist = (float) (earthRadius * c);
return dist;
}
public static String currencyId(double nominal){
Locale localID = new Locale("in", "ID");
NumberFormat rupiah = NumberFormat.getCurrencyInstance(localID);
return rupiah.format(nominal);
}
public static String getRandom() {
int sizeOfRandomString=10;
final Random random=new Random();
final StringBuilder sb=new StringBuilder(sizeOfRandomString);
for(int i=0;i<sizeOfRandomString;++i)
sb.append(ALLOWED_CHARACTERS.charAt(random.nextInt(ALLOWED_CHARACTERS.length())));
return sb.toString()+".jpg";
}
/*public static List<Credit> creditList(){
List<Credit> list = new ArrayList<>();
list.add(new Credit(true, R.drawable.ic_barcode_scanner, "com.vivekkaushik.datepicker:datePickerTimeline:0.0.4", "https://github.com/101Loop/DatePickerTimeline"));
list.add(new Credit(true, R.drawable.ic_barcode_scanner, "io.reactivex.rxjava2:rxjava:2.2.12", "https://github.com/ReactiveX/RxJava"));
list.add(new Credit(true, R.drawable.ic_barcode_scanner, "com.tbruyelle.rxpermissions2:rxpermissions:0.9.5@aar", "https://github.com/tbruyelle/RxPermissions"));
list.add(new Credit(true, R.drawable.ic_barcode_scanner, "com.zhihu.android:matisse:0.5.3-beta3", "https://github.com/zhihu/Matisse"));
list.add(new Credit(true, R.drawable.ic_barcode_scanner, "com.github.bumptech.glide:glide:4.11.0", "https://github.com/bumptech/glide"));
list.add(new Credit(true, R.drawable.ic_barcode_scanner, "com.github.bumptech.glide:compiler:4.11.0", "https://github.com/bumptech/glide"));
list.add(new Credit(true, R.drawable.ic_barcode_scanner, "com.theartofdev.edmodo:android-image-cropper:2.8.0", "https://github.com/ArthurHub/Android-Image-Cropper"));
list.add(new Credit(true, R.drawable.ic_barcode_scanner, "de.hdodenhof:circleimageview:3.1.0", "https://github.com/hdodenhof/CircleImageView"));
list.add(new Credit(true, R.drawable.ic_barcode_scanner, "com.squareup.retrofit2:retrofit:2.3.0", "https://github.com/square/retrofit"));
list.add(new Credit(true, R.drawable.ic_barcode_scanner, "com.squareup.retrofit2:converter-gson:2.3.0", "https://github.com/square/retrofit"));
list.add(new Credit(true, R.drawable.ic_barcode_scanner, "com.schibstedspain.android:leku:8.0.0", "https://github.com/AdevintaSpain/Leku"));
list.add(new Credit(true, R.drawable.ic_barcode_scanner, "com.google.zxing:core:3.3.0", "https://github.com/zxing/zxing"));
list.add(new Credit(true, R.drawable.ic_barcode_scanner, "com.journeyapps:zxing-android-embedded:4.2.0", "https://github.com/journeyapps/zxing-android-embedded"));
list.add(new Credit(false, R.drawable.ic_barcode_scanner, "www.flaticon.com", "https://www.flaticon.com/"));
list.add(new Credit(false, R.drawable.ic_bell_active, "www.flaticon.com", "https://www.flaticon.com/"));
list.add(new Credit(false, R.drawable.ic_bell_inactive, "www.flaticon.com", "https://www.flaticon.com/"));
list.add(new Credit(false, R.drawable.ic_book_active, "www.flaticon.com", "https://www.flaticon.com/"));
list.add(new Credit(false, R.drawable.ic_book_inactive, "www.flaticon.com", "https://www.flaticon.com/"));
list.add(new Credit(false, R.drawable.ic_clock, "www.flaticon.com", "https://www.flaticon.com/"));
list.add(new Credit(false, R.drawable.ic_credit_card, "www.flaticon.com", "https://www.flaticon.com/"));
list.add(new Credit(false, R.drawable.ic_dashboard_active, "www.flaticon.com", "https://www.flaticon.com/"));
list.add(new Credit(false, R.drawable.ic_dashboard_inactive, "www.flaticon.com", "https://www.flaticon.com/"));
list.add(new Credit(false, R.drawable.ic_home_active, "www.flaticon.com", "https://www.flaticon.com/"));
list.add(new Credit(false, R.drawable.ic_home_inactive, "www.flaticon.com", "https://www.flaticon.com/"));
list.add(new Credit(false, R.drawable.ic_plus, "www.flaticon.com", "https://www.flaticon.com/"));
list.add(new Credit(false, R.drawable.ic_remove, "www.flaticon.com", "https://www.flaticon.com/"));
list.add(new Credit(false, R.drawable.ic_search, "www.flaticon.com", "https://www.flaticon.com/"));
list.add(new Credit(false, R.drawable.ic_soccer_field, "www.flaticon.com", "https://www.flaticon.com/"));
list.add(new Credit(false, R.drawable.ic_star, "www.flaticon.com", "https://www.flaticon.com/"));
list.add(new Credit(false, R.drawable.ic_user_active, "www.flaticon.com", "https://www.flaticon.com/"));
list.add(new Credit(false, R.drawable.ic_user_inactive, "www.flaticon.com", "https://www.flaticon.com/"));
list.add(new Credit(false, R.drawable.photo, "www.flaticon.com", "https://www.flaticon.com/"));
list.add(new Credit(false, R.drawable.user, "www.flaticon.com", "https://www.flaticon.com/"));
return list;
}*/
}
| UTF-8 | Java | 7,615 | java | Cons.java | Java | [
{
"context": "er:datePickerTimeline:0.0.4\", \"https://github.com/101Loop/DatePickerTimeline\"));\n list.add(new Credi",
"end": 3491,
"score": 0.9985472559928894,
"start": 3484,
"tag": "USERNAME",
"value": "101Loop"
},
{
"context": "tivex.rxjava2:rxjava:2.2.12\", \"https://github.com/ReactiveX/RxJava\"));\n list.add(new Credit(true, R.dr",
"end": 3647,
"score": 0.9980312585830688,
"start": 3638,
"tag": "USERNAME",
"value": "ReactiveX"
},
{
"context": "Credit(true, R.drawable.ic_barcode_scanner, \"com.tbruyelle.rxpermissions2:rxpermissions:0.9.5@aar\", \"h",
"end": 3732,
"score": 0.6568483710289001,
"start": 3730,
"tag": "USERNAME",
"value": "br"
},
{
"context": "it(true, R.drawable.ic_barcode_scanner, \"com.tbruyelle.rxpermissions2:rxpermissions:0.9.5@aar\", \"https:/",
"end": 3738,
"score": 0.6776146292686462,
"start": 3734,
"tag": "USERNAME",
"value": "elle"
},
{
"context": "ns2:rxpermissions:0.9.5@aar\", \"https://github.com/tbruyelle/RxPermissions\"));\n list.add(new Credit(tru",
"end": 3809,
"score": 0.9995282888412476,
"start": 3800,
"tag": "USERNAME",
"value": "tbruyelle"
},
{
"context": "android:matisse:0.5.3-beta3\", \"https://github.com/zhihu/Matisse\"));\n list.add(new Credit(true, R.d",
"end": 3959,
"score": 0.9968134760856628,
"start": 3954,
"tag": "USERNAME",
"value": "zhihu"
},
{
"context": "tech.glide:glide:4.11.0\", \"https://github.com/bumptech/glide\"));\n list.add(new Credit(true, R.dra",
"end": 4107,
"score": 0.5992896556854248,
"start": 4103,
"tag": "USERNAME",
"value": "tech"
},
{
"context": "android-image-cropper:2.8.0\", \"https://github.com/ArthurHub/Android-Image-Cropper\"));\n list.add(new Cr",
"end": 4415,
"score": 0.9984145760536194,
"start": 4406,
"tag": "USERNAME",
"value": "ArthurHub"
},
{
"context": "enhof:circleimageview:3.1.0\", \"https://github.com/hdodenhof/CircleImageView\"));\n list.add(new Credit(t",
"end": 4574,
"score": 0.9947174787521362,
"start": 4565,
"tag": "USERNAME",
"value": "hdodenhof"
},
{
"context": "up.retrofit2:retrofit:2.3.0\", \"https://github.com/square/retrofit\"));\n list.add(new Credit(true, R.",
"end": 4727,
"score": 0.9273600578308105,
"start": 4721,
"tag": "USERNAME",
"value": "square"
},
{
"context": "rofit2:converter-gson:2.3.0\", \"https://github.com/square/retrofit\"));\n list.add(new Credit(true, R.",
"end": 4879,
"score": 0.9087265133857727,
"start": 4873,
"tag": "USERNAME",
"value": "square"
},
{
"context": "tedspain.android:leku:8.0.0\", \"https://github.com/AdevintaSpain/Leku\"));\n list.add(new Credit(true, R.draw",
"end": 5032,
"score": 0.9443235993385315,
"start": 5019,
"tag": "USERNAME",
"value": "AdevintaSpain"
},
{
"context": "com.google.zxing:core:3.3.0\", \"https://github.com/zxing/zxing\"));\n list.add(new Credit(true, R.dra",
"end": 5163,
"score": 0.9937829971313477,
"start": 5158,
"tag": "USERNAME",
"value": "zxing"
},
{
"context": "xing-android-embedded:4.2.0\", \"https://github.com/journeyapps/zxing-android-embedded\"));\n list.add(new C",
"end": 5318,
"score": 0.9996185898780823,
"start": 5307,
"tag": "USERNAME",
"value": "journeyapps"
}
]
| null | []
| package id.t12ue.kalimutu.helpers;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Random;
import java.util.TimeZone;
public class Cons {
public static String KEY_USER="USERS";
public static String KEY_TRANSACTION="TRANSACTIONS";
public static String KEY_BANK="BANKS";
public static String KEY_PACKAGE="PACKAGES";
public static String KEY_PRODUCT="PRODUCTS";
public static String KEY_NOTIFICATION="NOTIFICATIONS";
public static String KEY_DETAIL="DETAILS";
public static String KEY_CART="CARTS";
public static String KEY_TOKEN="TOKENS";
public static String KEY_IMAGE="IMAGES";
private static final String ALLOWED_CHARACTERS ="0123456789QWERTYUIOPASDFGHJKLZXCBNM";
public static String status(int sts){
String status = null;
if (sts==-2){
status="Bukti pembayaran invalid";
} else if (sts==-1){
status="Pesanan dibatalkan";
} else if (sts==0){
status="Pesanan sedang disiapkan";
} else if (sts==1){
status="Menunggu verifikasi pemabayaran";
} else if (sts==2){
status="Pembayaran telah diverifikasi";
} else if (sts==3){
status="Pesanan telah diambil";
} else if (sts==4){
status="Pesanan telah dikembalikan";
}
return status;
}
public static String dateFormat(String dt){
String s=null;
if (!dt.equals("-")){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat formatID = new SimpleDateFormat("dd-MMM-yyyy");
TimeZone tz = TimeZone.getTimeZone("Asia/Jakarta");
formatID.setTimeZone(tz);
try {
s = formatID.format(sdf.parse(dt));
} catch (ParseException e) {
e.printStackTrace();
}
} else {
s="-";
}
return s;
}
public static float distFrom(double lat1, double lng1, double lat2, double lng2) {
double earthRadius = 6371000; //meters
double dLat = Math.toRadians(lat2-lat1);
double dLng = Math.toRadians(lng2-lng1);
double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
Math.sin(dLng/2) * Math.sin(dLng/2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
float dist = (float) (earthRadius * c);
return dist;
}
public static String currencyId(double nominal){
Locale localID = new Locale("in", "ID");
NumberFormat rupiah = NumberFormat.getCurrencyInstance(localID);
return rupiah.format(nominal);
}
public static String getRandom() {
int sizeOfRandomString=10;
final Random random=new Random();
final StringBuilder sb=new StringBuilder(sizeOfRandomString);
for(int i=0;i<sizeOfRandomString;++i)
sb.append(ALLOWED_CHARACTERS.charAt(random.nextInt(ALLOWED_CHARACTERS.length())));
return sb.toString()+".jpg";
}
/*public static List<Credit> creditList(){
List<Credit> list = new ArrayList<>();
list.add(new Credit(true, R.drawable.ic_barcode_scanner, "com.vivekkaushik.datepicker:datePickerTimeline:0.0.4", "https://github.com/101Loop/DatePickerTimeline"));
list.add(new Credit(true, R.drawable.ic_barcode_scanner, "io.reactivex.rxjava2:rxjava:2.2.12", "https://github.com/ReactiveX/RxJava"));
list.add(new Credit(true, R.drawable.ic_barcode_scanner, "com.tbruyelle.rxpermissions2:rxpermissions:0.9.5@aar", "https://github.com/tbruyelle/RxPermissions"));
list.add(new Credit(true, R.drawable.ic_barcode_scanner, "com.zhihu.android:matisse:0.5.3-beta3", "https://github.com/zhihu/Matisse"));
list.add(new Credit(true, R.drawable.ic_barcode_scanner, "com.github.bumptech.glide:glide:4.11.0", "https://github.com/bumptech/glide"));
list.add(new Credit(true, R.drawable.ic_barcode_scanner, "com.github.bumptech.glide:compiler:4.11.0", "https://github.com/bumptech/glide"));
list.add(new Credit(true, R.drawable.ic_barcode_scanner, "com.theartofdev.edmodo:android-image-cropper:2.8.0", "https://github.com/ArthurHub/Android-Image-Cropper"));
list.add(new Credit(true, R.drawable.ic_barcode_scanner, "de.hdodenhof:circleimageview:3.1.0", "https://github.com/hdodenhof/CircleImageView"));
list.add(new Credit(true, R.drawable.ic_barcode_scanner, "com.squareup.retrofit2:retrofit:2.3.0", "https://github.com/square/retrofit"));
list.add(new Credit(true, R.drawable.ic_barcode_scanner, "com.squareup.retrofit2:converter-gson:2.3.0", "https://github.com/square/retrofit"));
list.add(new Credit(true, R.drawable.ic_barcode_scanner, "com.schibstedspain.android:leku:8.0.0", "https://github.com/AdevintaSpain/Leku"));
list.add(new Credit(true, R.drawable.ic_barcode_scanner, "com.google.zxing:core:3.3.0", "https://github.com/zxing/zxing"));
list.add(new Credit(true, R.drawable.ic_barcode_scanner, "com.journeyapps:zxing-android-embedded:4.2.0", "https://github.com/journeyapps/zxing-android-embedded"));
list.add(new Credit(false, R.drawable.ic_barcode_scanner, "www.flaticon.com", "https://www.flaticon.com/"));
list.add(new Credit(false, R.drawable.ic_bell_active, "www.flaticon.com", "https://www.flaticon.com/"));
list.add(new Credit(false, R.drawable.ic_bell_inactive, "www.flaticon.com", "https://www.flaticon.com/"));
list.add(new Credit(false, R.drawable.ic_book_active, "www.flaticon.com", "https://www.flaticon.com/"));
list.add(new Credit(false, R.drawable.ic_book_inactive, "www.flaticon.com", "https://www.flaticon.com/"));
list.add(new Credit(false, R.drawable.ic_clock, "www.flaticon.com", "https://www.flaticon.com/"));
list.add(new Credit(false, R.drawable.ic_credit_card, "www.flaticon.com", "https://www.flaticon.com/"));
list.add(new Credit(false, R.drawable.ic_dashboard_active, "www.flaticon.com", "https://www.flaticon.com/"));
list.add(new Credit(false, R.drawable.ic_dashboard_inactive, "www.flaticon.com", "https://www.flaticon.com/"));
list.add(new Credit(false, R.drawable.ic_home_active, "www.flaticon.com", "https://www.flaticon.com/"));
list.add(new Credit(false, R.drawable.ic_home_inactive, "www.flaticon.com", "https://www.flaticon.com/"));
list.add(new Credit(false, R.drawable.ic_plus, "www.flaticon.com", "https://www.flaticon.com/"));
list.add(new Credit(false, R.drawable.ic_remove, "www.flaticon.com", "https://www.flaticon.com/"));
list.add(new Credit(false, R.drawable.ic_search, "www.flaticon.com", "https://www.flaticon.com/"));
list.add(new Credit(false, R.drawable.ic_soccer_field, "www.flaticon.com", "https://www.flaticon.com/"));
list.add(new Credit(false, R.drawable.ic_star, "www.flaticon.com", "https://www.flaticon.com/"));
list.add(new Credit(false, R.drawable.ic_user_active, "www.flaticon.com", "https://www.flaticon.com/"));
list.add(new Credit(false, R.drawable.ic_user_inactive, "www.flaticon.com", "https://www.flaticon.com/"));
list.add(new Credit(false, R.drawable.photo, "www.flaticon.com", "https://www.flaticon.com/"));
list.add(new Credit(false, R.drawable.user, "www.flaticon.com", "https://www.flaticon.com/"));
return list;
}*/
}
| 7,615 | 0.656336 | 0.64373 | 136 | 54.992645 | 47.05949 | 174 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.426471 | false | false | 15 |
08901dda2795c004a44ede8936aeb632407ba1eb | 17,798,344,484,289 | 308a854b343dc7243a89264df64600c63ce181ea | /src/main/java/com/nk/sp/MainClass.java | f752f3e87b95cdb773b56be0a65e1ebbc2599d40 | []
| no_license | nkarthikpsg/Spotify-Playlist | https://github.com/nkarthikpsg/Spotify-Playlist | e06ef8bc8b4133c01d53ba591a86aab1fa22291f | ab8a6f2f8ba7b1ab84b550777f548b0060e13467 | refs/heads/master | 2020-07-20T08:43:04.316000 | 2019-09-05T18:05:23 | 2019-09-05T18:05:23 | 206,610,929 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.nk.sp;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import com.nk.sp.dto.TrackInfo;
import com.nk.sp.dto.Tracks;
import com.nk.sp.helper.SpotifyMatchStats;
import com.nk.sp.helper.SpotifyRefreshTokenHelper;
import com.nk.sp.helper.SpotifyTrackSearchHelper;
public class MainClass
{
public static void main(String args[])
{
SpotifyMatchStats stats = new SpotifyMatchStats();
// Tracks tracks = SaavnTrackHelper.instance().getTracks("https://www.saavn.com/s/featured/tamil/Weekly_Top_15");
Tracks tracks = new Tracks();
TrackInfo trackInfo = new TrackInfo();
trackInfo.setAlbumName("Bigil");
trackInfo.setTrackName("Singappenney");
tracks.setTrackInfoList(Arrays.asList(trackInfo));
String refreshToken = SpotifyRefreshTokenHelper.instance().getRefreshToken();
List<String> spotifyTracks = SpotifyTrackSearchHelper.instance().getSpotifyTracks(tracks, stats, refreshToken);
System.out.println(spotifyTracks);
System.out.println(stats);
}
public static void main1(String args[])
{
Document doc = null;
try
{
doc = Jsoup.connect("https://www.saavn.com/s/featured/tamil/Highway_Hits/foVAPRKAlmw").get();
}
catch (IOException e)
{
e.printStackTrace();
}
Elements contents = doc.select("div[class=details content-list");
contents.forEach(con -> {
System.out.println(con.select("p[class=song-name ellip]").first().textNodes().get(0).text());
System.out.println(con.select("p[class=album-name ellip]").first().textNodes().get(0).text());
});
// System.out.println(
// new LuceneLevenshteinDistance().getDistance("Thaana Serndha Kottam", "Thaana Serndha Koottam"));
// OutputStream outputStream = null;
// try
// {
// URL url = new URL("http://tamilfreemp3s.net/down.php?file=Tamil%202017%20Songs/Thaanaa%20Serndha%20Koottam/64/Sodakku.mp3");
//
// URLConnection conn = url.openConnection();
// conn.addRequestProperty("User-Agent",
// "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
// InputStream is = conn.getInputStream();
//
// outputStream = new FileOutputStream(new File("/A/temp/file.mp3"));
// byte[] buffer = new byte[4096];
// int len;
// while ((len = is.read(buffer)) > 0) {
// outputStream.write(buffer, 0, len);
// }
// }
// catch (Exception e)
// {
// e.printStackTrace();
// }
// finally
// {
// if(outputStream != null)
// try
// {
// outputStream.close();
// }
// catch (IOException e)
// {
// e.printStackTrace();
// }
// }
}
}
| UTF-8 | Java | 3,372 | java | MainClass.java | Java | [
{
"context": "nDistance().getDistance(\"Thaana Serndha Kottam\", \"Thaana Serndha Koottam\"));\n // OutputStream outputStream =",
"end": 1977,
"score": 0.7010667324066162,
"start": 1955,
"tag": "NAME",
"value": "Thaana Serndha Koottam"
}
]
| null | []
| package com.nk.sp;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import com.nk.sp.dto.TrackInfo;
import com.nk.sp.dto.Tracks;
import com.nk.sp.helper.SpotifyMatchStats;
import com.nk.sp.helper.SpotifyRefreshTokenHelper;
import com.nk.sp.helper.SpotifyTrackSearchHelper;
public class MainClass
{
public static void main(String args[])
{
SpotifyMatchStats stats = new SpotifyMatchStats();
// Tracks tracks = SaavnTrackHelper.instance().getTracks("https://www.saavn.com/s/featured/tamil/Weekly_Top_15");
Tracks tracks = new Tracks();
TrackInfo trackInfo = new TrackInfo();
trackInfo.setAlbumName("Bigil");
trackInfo.setTrackName("Singappenney");
tracks.setTrackInfoList(Arrays.asList(trackInfo));
String refreshToken = SpotifyRefreshTokenHelper.instance().getRefreshToken();
List<String> spotifyTracks = SpotifyTrackSearchHelper.instance().getSpotifyTracks(tracks, stats, refreshToken);
System.out.println(spotifyTracks);
System.out.println(stats);
}
public static void main1(String args[])
{
Document doc = null;
try
{
doc = Jsoup.connect("https://www.saavn.com/s/featured/tamil/Highway_Hits/foVAPRKAlmw").get();
}
catch (IOException e)
{
e.printStackTrace();
}
Elements contents = doc.select("div[class=details content-list");
contents.forEach(con -> {
System.out.println(con.select("p[class=song-name ellip]").first().textNodes().get(0).text());
System.out.println(con.select("p[class=album-name ellip]").first().textNodes().get(0).text());
});
// System.out.println(
// new LuceneLevenshteinDistance().getDistance("Thaana Serndha Kottam", "<NAME>"));
// OutputStream outputStream = null;
// try
// {
// URL url = new URL("http://tamilfreemp3s.net/down.php?file=Tamil%202017%20Songs/Thaanaa%20Serndha%20Koottam/64/Sodakku.mp3");
//
// URLConnection conn = url.openConnection();
// conn.addRequestProperty("User-Agent",
// "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
// InputStream is = conn.getInputStream();
//
// outputStream = new FileOutputStream(new File("/A/temp/file.mp3"));
// byte[] buffer = new byte[4096];
// int len;
// while ((len = is.read(buffer)) > 0) {
// outputStream.write(buffer, 0, len);
// }
// }
// catch (Exception e)
// {
// e.printStackTrace();
// }
// finally
// {
// if(outputStream != null)
// try
// {
// outputStream.close();
// }
// catch (IOException e)
// {
// e.printStackTrace();
// }
// }
}
}
| 3,356 | 0.534698 | 0.524614 | 93 | 35.258064 | 31.979799 | 146 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.548387 | false | false | 13 |
4a48b0ffe69767f11227eabb5ee51b742feab171 | 14,654,428,424,910 | bd3205b3fb2305bb5143bf8da0705772f32a1cae | /src/main/java/edu/ilstu/reversecomplementapplication/controllers/ReverseComplementController.java | 937a60174f8b1a1ac4023c36a78d962495a94ffe | []
| no_license | CodingBash/ReverseComplementWebApplication | https://github.com/CodingBash/ReverseComplementWebApplication | 3f9473b0c1ae5eaba8dcc9f47aaa8d54e198b651 | 7393d5423e3474e04046c1c897f45a3c456f84f1 | refs/heads/master | 2021-01-10T18:21:01.780000 | 2016-03-27T03:05:50 | 2016-03-27T03:05:50 | 52,610,542 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package edu.ilstu.reversecomplementapplication.controllers;
import java.util.LinkedList;
import javax.servlet.http.HttpSession;
import org.biojava.nbio.core.exceptions.CompoundNotFoundException;
import org.biojava.nbio.core.sequence.DNASequence;
import org.biojava.nbio.core.sequence.RNASequence;
import org.biojava.nbio.core.sequence.compound.NucleotideCompound;
import org.biojava.nbio.core.sequence.template.AbstractSequence;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import edu.ilstu.reversecomplementapplication.components.ApplicationUtilityImpl;
import edu.ilstu.reversecomplementapplication.models.Sequence;
import edu.ilstu.reversecomplementapplication.models.SequenceContainer;
/**
* Controller handles server logic in the index.jsp page
*
* @author Bash
*
*/
@Controller
public class ReverseComplementController
{
private static final Logger logger = LoggerFactory.getLogger(ReverseComplementController.class);
private static final String reverseComplementPage = "reversecomplementtool/reversecomplement";
@Autowired
ApplicationUtilityImpl applicationUtility;
/**
* Empty URL field goes to the index.jsp landing page
*
* @return redire8ct to index.jsp
*/
@RequestMapping(value = "/reversecomplement")
public ModelAndView getIndex(HttpSession session)
{
ModelAndView mav = new ModelAndView(reverseComplementPage);
addFormAttribute();
// Retrieve sequence container from session
SequenceContainer sequenceContainer = this.retrieveSequenceContainer(session);
// Add sequence to the ModelAndView
mav.addObject("container", sequenceContainer.getSequenceContainer());
return mav;
}
/**
* Get the reverse complement of the submitted DNAsequence
*
* @param stringSequence
* String of sequence to be submitted
* @param model
* object container sent to be used in the view
* @return redirect to index.jsp
*/
@RequestMapping(value = "/submitSequence.do", method = RequestMethod.POST)
public ModelAndView submitSequence(@ModelAttribute("sequenceFormAttribute") Sequence sequenceModel,
HttpSession session)
{
ModelAndView mav = new ModelAndView(reverseComplementPage);
// Get stringSequence
String stringSequence = sequenceModel.getSequence();
// Create the sequence from the @RequestParam
AbstractSequence<NucleotideCompound> abstractSequence = createSequence(stringSequence);
/*
* Get and set reverse complement
*/
if (abstractSequence != null && abstractSequence.getLength() != 0)
{
try
{
if (abstractSequence instanceof DNASequence)
{
abstractSequence = new DNASequence(
((DNASequence) abstractSequence).getReverseComplement().getSequenceAsString());
} else if (abstractSequence instanceof RNASequence)
{
abstractSequence = new RNASequence(
((RNASequence) abstractSequence).getReverseComplement().getSequenceAsString());
}
/*
* Convert regular sequence to FASTA sequence
*/
String fastaHeader = "";
try
{
fastaHeader = applicationUtility.extractFastaHeader(stringSequence);
} catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
String regularSequence = abstractSequence.toString();
String fastaSequence = applicationUtility.convertToFastaSequence(fastaHeader, regularSequence);
sequenceModel.setResultSequence(fastaSequence);
// Add FASTA sequence to model
} catch (CompoundNotFoundException e)
{
e.printStackTrace();
}
}
// addFormAttribute(sequenceModel);
// Retrieve sequence container from session
SequenceContainer sequenceContainer = this.retrieveSequenceContainer(session);
// Add sequence to the ModelAndView
mav.addObject("container", sequenceContainer.getSequenceContainer());
return mav;
}
/**
* Save sequence in server container
*
* @param stringSequence
* String of sequence to be saved
* @param model
* object container sent to be used in the view
* @param session
* Spring session object
* @return redirect to index.jsp
*/
@RequestMapping(value = "/saveSequence.do", method = RequestMethod.POST)
public ModelAndView saveSequence(@RequestParam("sequence") String stringSequence,
@ModelAttribute("sequenceFormAttribute") Sequence sequenceModel, HttpSession session)
{
ModelAndView mav = new ModelAndView(reverseComplementPage);
// Retrieve sequence container from session
SequenceContainer sequenceContainer = this.retrieveSequenceContainer(session);
// Create the sequence from the @RequestParam
AbstractSequence<NucleotideCompound> abstractSequence = createSequence(stringSequence);
// Add the DNASequence
sequenceContainer.addSequenceToContainer(abstractSequence);
// Add updated sequenceContainer back to session
session.setAttribute("sequenceContainer", sequenceContainer);
// Add sequence to the ModelAndView
mav.addObject("container", sequenceContainer.getSequenceContainer());
// Refresh the index page
return mav;
}
/**
* Edit sequence in server container
*
* @param stringSequence
* String of sequence to be saved
* @param model
* object container sent to be used in the view
* @param session
* Spring session object
* @return redirect to index.jsp
*/// TODO: Error handling.
@RequestMapping(value = "/editSequence.do", method = RequestMethod.POST)
public ModelAndView editSequence(@RequestParam("sequence") String stringSequence, @RequestParam("index") int index,
@ModelAttribute("sequenceFormAttribute") Sequence sequenceModel, HttpSession session)
{
ModelAndView mav = new ModelAndView(reverseComplementPage);
// Retrieve sequence container from session
SequenceContainer sequenceContainer = this.retrieveSequenceContainer(session);
// Create the sequence from the @RequestParam
AbstractSequence<NucleotideCompound> abstractSequence = createSequence(stringSequence);
// Make the edit changes in the sequence container
sequenceContainer.editSequenceInContainer(index, abstractSequence);
// Add updated sequenceContainer back to session
session.setAttribute("sequenceContainer", sequenceContainer);
// Add sequence to the ModelAndView
mav.addObject("container", sequenceContainer.getSequenceContainer());
// Refresh the index page
return mav;
}
/**
* Delete sequence in server container
*
* @param model
* object container sent to be used in the view
* @param session
* Spring session object
* @return redirect to index.jsp
*/// TODO: Don't delete, validate request
@RequestMapping(value = "/deleteSequence.do", method = RequestMethod.POST)
public ModelAndView deleteSequence(@RequestParam("index") int index,
@ModelAttribute("sequenceFormAttribute") Sequence sequence, HttpSession session)
{
ModelAndView mav = new ModelAndView(reverseComplementPage);
// Retrieve sequence container from session
SequenceContainer sequenceContainer = this.retrieveSequenceContainer(session);
// Delete the sequence
try
{
sequenceContainer.removeSequenceInContainer(index);
} catch (IndexOutOfBoundsException ioobe)
{
ioobe.printStackTrace();
} catch (Exception e)
{
e.printStackTrace();
}
// Add updated sequenceContainer back to session
session.setAttribute("sequenceContainer", sequenceContainer);
// Add sequence to the ModelAndView
mav.addObject("container", sequenceContainer.getSequenceContainer());
// Refresh the index page
return mav;
}
/**
* Delete all sequences in server container
*
* @param model
* object container sent to be used in the view
* @param session
* Spring session object
* @return redirect to index.jsp
*/
@RequestMapping(value = "/deleteAllSequences.do", method = RequestMethod.POST)
public ModelAndView deleteAllSequences(@ModelAttribute("sequenceFormAttribute") Sequence sequenceModel,
HttpSession session)
{
ModelAndView mav = new ModelAndView(reverseComplementPage);
// Retrieve sequence container from session
SequenceContainer sequenceContainer = this.retrieveSequenceContainer(session);
// Delete the sequence
try
{
sequenceContainer.removeAllSequencesInContainer();
} catch (Exception e)
{
e.printStackTrace();
}
// Add updated sequenceContainer back to session
session.setAttribute("sequenceContainer", sequenceContainer);
// Add sequence to the ModelAndView
mav.addObject("container", sequenceContainer.getSequenceContainer());
// Refresh the index page
return mav;
}
/**
* Delete a list of selected indexes from the list of sequences
*
* @param stringIndexList
* list of indexes to remove
* @param model
* object container sent to be used in the view
* @param session
* Spring session object
* @return redirect to index.jsp
*/
@RequestMapping(value = "/deleteSelectedSequences.do", method = RequestMethod.POST)
public ModelAndView deleteSelectedSequences(@RequestParam("indexList") String[] stringIndexList,
@ModelAttribute("sequenceFormAttribute") Sequence sequenceModel, HttpSession session)
{
ModelAndView mav = new ModelAndView(reverseComplementPage);
// Retrieve sequence container from session
SequenceContainer sequenceContainer = this.retrieveSequenceContainer(session);
// Convert String[] to int[]
int[] intIndexList = applicationUtility.convertStringArrayToIntArray(stringIndexList);
// Delete the sequences
try
{
sequenceContainer.removeSelectedSequencesInContainer(intIndexList);
} catch (IndexOutOfBoundsException ioobe)
{
ioobe.printStackTrace();
} catch (Exception e)
{
e.printStackTrace();
}
// Add updated sequenceContainer back to session
session.setAttribute("sequenceContainer", sequenceContainer);
// Add sequence to the ModelAndView
mav.addObject("container", sequenceContainer.getSequenceContainer());
// Refresh the index page
return mav;
}
/**
* Retrieves {@link SequenceContainer} from the (@link HttpSession}
*
* @param session
* Spring session object
* @return sequenceContainer from the {@link HttpSession}
*/
private SequenceContainer retrieveSequenceContainer(HttpSession session)
{
// Insert session attribute into generic object
Object objectedSequenceContainer = session.getAttribute("sequenceContainer");
// Create a SequenceContainer object
SequenceContainer sequenceContainer = null;
// Check if the object is an instance of a SequenceContainer
if (objectedSequenceContainer instanceof SequenceContainer)
{
sequenceContainer = (SequenceContainer) objectedSequenceContainer;
}
// If not, make a new SequenceContainer
else
{
sequenceContainer = new SequenceContainer(new LinkedList<AbstractSequence<NucleotideCompound>>());
}
return sequenceContainer;
}
/**
* Creates an {@link AbstractSequence}<{@link NucleotideCompound}> from a
* {@link String} sequence
*
* @param stringSequence
* sequence to become an {@link AbstractSequence}<
* {@link NucleotideCompound}>
* @return the {@link AbstractSequence}<{@link NucleotideCompound}>
*/
private AbstractSequence<NucleotideCompound> createSequence(String stringSequence)
{
AbstractSequence<NucleotideCompound> sequence = null;
String formattedSequence = "";
try
{
formattedSequence = applicationUtility.editStringSequence(stringSequence);
} catch (Exception e3)
{
e3.printStackTrace();
}
if (applicationUtility.isDNA(formattedSequence))
{
try
{
sequence = new DNASequence(formattedSequence);
} catch (Exception e)
{
e.printStackTrace();
try
{
sequence = new DNASequence(stringSequence);
} catch (CompoundNotFoundException e1)
{
e1.printStackTrace();
}
}
} else if (applicationUtility.isRNA(formattedSequence))
{
try
{
sequence = new RNASequence(formattedSequence);
} catch (Exception e)
{
e.printStackTrace();
try
{
sequence = new DNASequence(stringSequence);
} catch (CompoundNotFoundException e1)
{
e1.printStackTrace();
}
}
}
return sequence;
}
@ModelAttribute("sequenceFormAttribute")
private Sequence addFormAttribute()
{
Sequence sequence = new Sequence();
return sequence;
}
@ModelAttribute("sequenceFormAttribute")
private Sequence addFormAttribute(Sequence sequence)
{
return sequence;
}
}
| UTF-8 | Java | 13,328 | java | ReverseComplementController.java | Java | [
{
"context": "erver logic in the index.jsp page\r\n * \r\n * @author Bash\r\n *\r\n */\r\n@Controller\r\npublic class ReverseComple",
"end": 1230,
"score": 0.980787992477417,
"start": 1226,
"tag": "NAME",
"value": "Bash"
}
]
| null | []
| package edu.ilstu.reversecomplementapplication.controllers;
import java.util.LinkedList;
import javax.servlet.http.HttpSession;
import org.biojava.nbio.core.exceptions.CompoundNotFoundException;
import org.biojava.nbio.core.sequence.DNASequence;
import org.biojava.nbio.core.sequence.RNASequence;
import org.biojava.nbio.core.sequence.compound.NucleotideCompound;
import org.biojava.nbio.core.sequence.template.AbstractSequence;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import edu.ilstu.reversecomplementapplication.components.ApplicationUtilityImpl;
import edu.ilstu.reversecomplementapplication.models.Sequence;
import edu.ilstu.reversecomplementapplication.models.SequenceContainer;
/**
* Controller handles server logic in the index.jsp page
*
* @author Bash
*
*/
@Controller
public class ReverseComplementController
{
private static final Logger logger = LoggerFactory.getLogger(ReverseComplementController.class);
private static final String reverseComplementPage = "reversecomplementtool/reversecomplement";
@Autowired
ApplicationUtilityImpl applicationUtility;
/**
* Empty URL field goes to the index.jsp landing page
*
* @return redire8ct to index.jsp
*/
@RequestMapping(value = "/reversecomplement")
public ModelAndView getIndex(HttpSession session)
{
ModelAndView mav = new ModelAndView(reverseComplementPage);
addFormAttribute();
// Retrieve sequence container from session
SequenceContainer sequenceContainer = this.retrieveSequenceContainer(session);
// Add sequence to the ModelAndView
mav.addObject("container", sequenceContainer.getSequenceContainer());
return mav;
}
/**
* Get the reverse complement of the submitted DNAsequence
*
* @param stringSequence
* String of sequence to be submitted
* @param model
* object container sent to be used in the view
* @return redirect to index.jsp
*/
@RequestMapping(value = "/submitSequence.do", method = RequestMethod.POST)
public ModelAndView submitSequence(@ModelAttribute("sequenceFormAttribute") Sequence sequenceModel,
HttpSession session)
{
ModelAndView mav = new ModelAndView(reverseComplementPage);
// Get stringSequence
String stringSequence = sequenceModel.getSequence();
// Create the sequence from the @RequestParam
AbstractSequence<NucleotideCompound> abstractSequence = createSequence(stringSequence);
/*
* Get and set reverse complement
*/
if (abstractSequence != null && abstractSequence.getLength() != 0)
{
try
{
if (abstractSequence instanceof DNASequence)
{
abstractSequence = new DNASequence(
((DNASequence) abstractSequence).getReverseComplement().getSequenceAsString());
} else if (abstractSequence instanceof RNASequence)
{
abstractSequence = new RNASequence(
((RNASequence) abstractSequence).getReverseComplement().getSequenceAsString());
}
/*
* Convert regular sequence to FASTA sequence
*/
String fastaHeader = "";
try
{
fastaHeader = applicationUtility.extractFastaHeader(stringSequence);
} catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
String regularSequence = abstractSequence.toString();
String fastaSequence = applicationUtility.convertToFastaSequence(fastaHeader, regularSequence);
sequenceModel.setResultSequence(fastaSequence);
// Add FASTA sequence to model
} catch (CompoundNotFoundException e)
{
e.printStackTrace();
}
}
// addFormAttribute(sequenceModel);
// Retrieve sequence container from session
SequenceContainer sequenceContainer = this.retrieveSequenceContainer(session);
// Add sequence to the ModelAndView
mav.addObject("container", sequenceContainer.getSequenceContainer());
return mav;
}
/**
* Save sequence in server container
*
* @param stringSequence
* String of sequence to be saved
* @param model
* object container sent to be used in the view
* @param session
* Spring session object
* @return redirect to index.jsp
*/
@RequestMapping(value = "/saveSequence.do", method = RequestMethod.POST)
public ModelAndView saveSequence(@RequestParam("sequence") String stringSequence,
@ModelAttribute("sequenceFormAttribute") Sequence sequenceModel, HttpSession session)
{
ModelAndView mav = new ModelAndView(reverseComplementPage);
// Retrieve sequence container from session
SequenceContainer sequenceContainer = this.retrieveSequenceContainer(session);
// Create the sequence from the @RequestParam
AbstractSequence<NucleotideCompound> abstractSequence = createSequence(stringSequence);
// Add the DNASequence
sequenceContainer.addSequenceToContainer(abstractSequence);
// Add updated sequenceContainer back to session
session.setAttribute("sequenceContainer", sequenceContainer);
// Add sequence to the ModelAndView
mav.addObject("container", sequenceContainer.getSequenceContainer());
// Refresh the index page
return mav;
}
/**
* Edit sequence in server container
*
* @param stringSequence
* String of sequence to be saved
* @param model
* object container sent to be used in the view
* @param session
* Spring session object
* @return redirect to index.jsp
*/// TODO: Error handling.
@RequestMapping(value = "/editSequence.do", method = RequestMethod.POST)
public ModelAndView editSequence(@RequestParam("sequence") String stringSequence, @RequestParam("index") int index,
@ModelAttribute("sequenceFormAttribute") Sequence sequenceModel, HttpSession session)
{
ModelAndView mav = new ModelAndView(reverseComplementPage);
// Retrieve sequence container from session
SequenceContainer sequenceContainer = this.retrieveSequenceContainer(session);
// Create the sequence from the @RequestParam
AbstractSequence<NucleotideCompound> abstractSequence = createSequence(stringSequence);
// Make the edit changes in the sequence container
sequenceContainer.editSequenceInContainer(index, abstractSequence);
// Add updated sequenceContainer back to session
session.setAttribute("sequenceContainer", sequenceContainer);
// Add sequence to the ModelAndView
mav.addObject("container", sequenceContainer.getSequenceContainer());
// Refresh the index page
return mav;
}
/**
* Delete sequence in server container
*
* @param model
* object container sent to be used in the view
* @param session
* Spring session object
* @return redirect to index.jsp
*/// TODO: Don't delete, validate request
@RequestMapping(value = "/deleteSequence.do", method = RequestMethod.POST)
public ModelAndView deleteSequence(@RequestParam("index") int index,
@ModelAttribute("sequenceFormAttribute") Sequence sequence, HttpSession session)
{
ModelAndView mav = new ModelAndView(reverseComplementPage);
// Retrieve sequence container from session
SequenceContainer sequenceContainer = this.retrieveSequenceContainer(session);
// Delete the sequence
try
{
sequenceContainer.removeSequenceInContainer(index);
} catch (IndexOutOfBoundsException ioobe)
{
ioobe.printStackTrace();
} catch (Exception e)
{
e.printStackTrace();
}
// Add updated sequenceContainer back to session
session.setAttribute("sequenceContainer", sequenceContainer);
// Add sequence to the ModelAndView
mav.addObject("container", sequenceContainer.getSequenceContainer());
// Refresh the index page
return mav;
}
/**
* Delete all sequences in server container
*
* @param model
* object container sent to be used in the view
* @param session
* Spring session object
* @return redirect to index.jsp
*/
@RequestMapping(value = "/deleteAllSequences.do", method = RequestMethod.POST)
public ModelAndView deleteAllSequences(@ModelAttribute("sequenceFormAttribute") Sequence sequenceModel,
HttpSession session)
{
ModelAndView mav = new ModelAndView(reverseComplementPage);
// Retrieve sequence container from session
SequenceContainer sequenceContainer = this.retrieveSequenceContainer(session);
// Delete the sequence
try
{
sequenceContainer.removeAllSequencesInContainer();
} catch (Exception e)
{
e.printStackTrace();
}
// Add updated sequenceContainer back to session
session.setAttribute("sequenceContainer", sequenceContainer);
// Add sequence to the ModelAndView
mav.addObject("container", sequenceContainer.getSequenceContainer());
// Refresh the index page
return mav;
}
/**
* Delete a list of selected indexes from the list of sequences
*
* @param stringIndexList
* list of indexes to remove
* @param model
* object container sent to be used in the view
* @param session
* Spring session object
* @return redirect to index.jsp
*/
@RequestMapping(value = "/deleteSelectedSequences.do", method = RequestMethod.POST)
public ModelAndView deleteSelectedSequences(@RequestParam("indexList") String[] stringIndexList,
@ModelAttribute("sequenceFormAttribute") Sequence sequenceModel, HttpSession session)
{
ModelAndView mav = new ModelAndView(reverseComplementPage);
// Retrieve sequence container from session
SequenceContainer sequenceContainer = this.retrieveSequenceContainer(session);
// Convert String[] to int[]
int[] intIndexList = applicationUtility.convertStringArrayToIntArray(stringIndexList);
// Delete the sequences
try
{
sequenceContainer.removeSelectedSequencesInContainer(intIndexList);
} catch (IndexOutOfBoundsException ioobe)
{
ioobe.printStackTrace();
} catch (Exception e)
{
e.printStackTrace();
}
// Add updated sequenceContainer back to session
session.setAttribute("sequenceContainer", sequenceContainer);
// Add sequence to the ModelAndView
mav.addObject("container", sequenceContainer.getSequenceContainer());
// Refresh the index page
return mav;
}
/**
* Retrieves {@link SequenceContainer} from the (@link HttpSession}
*
* @param session
* Spring session object
* @return sequenceContainer from the {@link HttpSession}
*/
private SequenceContainer retrieveSequenceContainer(HttpSession session)
{
// Insert session attribute into generic object
Object objectedSequenceContainer = session.getAttribute("sequenceContainer");
// Create a SequenceContainer object
SequenceContainer sequenceContainer = null;
// Check if the object is an instance of a SequenceContainer
if (objectedSequenceContainer instanceof SequenceContainer)
{
sequenceContainer = (SequenceContainer) objectedSequenceContainer;
}
// If not, make a new SequenceContainer
else
{
sequenceContainer = new SequenceContainer(new LinkedList<AbstractSequence<NucleotideCompound>>());
}
return sequenceContainer;
}
/**
* Creates an {@link AbstractSequence}<{@link NucleotideCompound}> from a
* {@link String} sequence
*
* @param stringSequence
* sequence to become an {@link AbstractSequence}<
* {@link NucleotideCompound}>
* @return the {@link AbstractSequence}<{@link NucleotideCompound}>
*/
private AbstractSequence<NucleotideCompound> createSequence(String stringSequence)
{
AbstractSequence<NucleotideCompound> sequence = null;
String formattedSequence = "";
try
{
formattedSequence = applicationUtility.editStringSequence(stringSequence);
} catch (Exception e3)
{
e3.printStackTrace();
}
if (applicationUtility.isDNA(formattedSequence))
{
try
{
sequence = new DNASequence(formattedSequence);
} catch (Exception e)
{
e.printStackTrace();
try
{
sequence = new DNASequence(stringSequence);
} catch (CompoundNotFoundException e1)
{
e1.printStackTrace();
}
}
} else if (applicationUtility.isRNA(formattedSequence))
{
try
{
sequence = new RNASequence(formattedSequence);
} catch (Exception e)
{
e.printStackTrace();
try
{
sequence = new DNASequence(stringSequence);
} catch (CompoundNotFoundException e1)
{
e1.printStackTrace();
}
}
}
return sequence;
}
@ModelAttribute("sequenceFormAttribute")
private Sequence addFormAttribute()
{
Sequence sequence = new Sequence();
return sequence;
}
@ModelAttribute("sequenceFormAttribute")
private Sequence addFormAttribute(Sequence sequence)
{
return sequence;
}
}
| 13,328 | 0.720738 | 0.719988 | 420 | 29.733334 | 28.333227 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.935714 | false | false | 13 |
95dbcff0e058201adab13a6c95d5427c1c1c3766 | 29,102,698,409,781 | 1eda89849e760fbf54d7dc2facb85f74ee7d5bb8 | /src/codingQuestions/Insert5.java | 507f56c1df0b15f3fe18591c032571ec5ae25420 | []
| no_license | rrohitmaheshwari/JavaPractice | https://github.com/rrohitmaheshwari/JavaPractice | 8848007944c013585b5633e3ed55dd5dba740da0 | febfd40d966987f7505e24fc56cf5582cc9b5636 | refs/heads/master | 2022-06-16T15:50:08.303000 | 2022-05-31T03:46:32 | 2022-05-31T03:46:32 | 211,639,994 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package codingQuestions;
public class Insert5 {
public static void main(String[] args) {
System.out.println(solution(268) + " " + solution2(268));
System.out.println(solution(670)+ " " + solution2(670));
System.out.println(solution(0)+ " " + solution2(0));
System.out.println(solution(-0)+ " " + solution2(-0));
System.out.println(solution(-1)+ " " + solution2(-1));
System.out.println(solution(-999)+ " " + solution2(-999));
System.out.println(solution(-439)+ " " + solution2(-439));
System.out.println(solution(-4539)+ " " + solution2(-4539));
System.out.println(solution(-8000)+ " " + solution2(-8000));
System.out.println(solution(8000)+ " " + solution2(8000));
// for(int i=-8000;i<=8000;i++){
// if(solution(i)!=solution2(i))
// System.out.println(i +" "+ solution(i) + " "+solution2(i));
// }
}
public static int solution(int N) {
StringBuilder s = new StringBuilder(String.valueOf(Math.abs(N)));
int sign = 1; //positive
if (N < 0) {
sign = -1; //negative number
}
int i = 0;
if (sign == 1) {
while (i < s.length()) {
if ((s.charAt(i) - '0' >= 5))
i++;
else
break;
}
} else {
while (i < s.length()) {
if ((s.charAt(i) - '0' <= 5))
i++;
else
break;
}
}
s.insert(i, '5');
int val = Integer.parseInt(s.toString());
return sign * val;
}
public static int solution2(int N) {
StringBuilder s = new StringBuilder(String.valueOf(Math.abs(N)));
int sign = 1; //positive
int res = Integer.parseInt(s+"5");
if (N < 0) {
sign = -1; //negative number
}
int i = 0;
if (sign == 1) {
while (i < s.length()) {
StringBuilder sb = new StringBuilder(s);
sb.insert(i, '5');
res = Math.max(res,Integer.parseInt(sb.toString()));
i++;
}
} else {
res=-1*res;
while (i < s.length()) {
StringBuilder sb = new StringBuilder(s);
sb.insert(i, '5');
res = Math.max(res,-1*Integer.parseInt(sb.toString()));
i++;
}
}
return res;
}
}
| UTF-8 | Java | 2,550 | java | Insert5.java | Java | []
| null | []
| package codingQuestions;
public class Insert5 {
public static void main(String[] args) {
System.out.println(solution(268) + " " + solution2(268));
System.out.println(solution(670)+ " " + solution2(670));
System.out.println(solution(0)+ " " + solution2(0));
System.out.println(solution(-0)+ " " + solution2(-0));
System.out.println(solution(-1)+ " " + solution2(-1));
System.out.println(solution(-999)+ " " + solution2(-999));
System.out.println(solution(-439)+ " " + solution2(-439));
System.out.println(solution(-4539)+ " " + solution2(-4539));
System.out.println(solution(-8000)+ " " + solution2(-8000));
System.out.println(solution(8000)+ " " + solution2(8000));
// for(int i=-8000;i<=8000;i++){
// if(solution(i)!=solution2(i))
// System.out.println(i +" "+ solution(i) + " "+solution2(i));
// }
}
public static int solution(int N) {
StringBuilder s = new StringBuilder(String.valueOf(Math.abs(N)));
int sign = 1; //positive
if (N < 0) {
sign = -1; //negative number
}
int i = 0;
if (sign == 1) {
while (i < s.length()) {
if ((s.charAt(i) - '0' >= 5))
i++;
else
break;
}
} else {
while (i < s.length()) {
if ((s.charAt(i) - '0' <= 5))
i++;
else
break;
}
}
s.insert(i, '5');
int val = Integer.parseInt(s.toString());
return sign * val;
}
public static int solution2(int N) {
StringBuilder s = new StringBuilder(String.valueOf(Math.abs(N)));
int sign = 1; //positive
int res = Integer.parseInt(s+"5");
if (N < 0) {
sign = -1; //negative number
}
int i = 0;
if (sign == 1) {
while (i < s.length()) {
StringBuilder sb = new StringBuilder(s);
sb.insert(i, '5');
res = Math.max(res,Integer.parseInt(sb.toString()));
i++;
}
} else {
res=-1*res;
while (i < s.length()) {
StringBuilder sb = new StringBuilder(s);
sb.insert(i, '5');
res = Math.max(res,-1*Integer.parseInt(sb.toString()));
i++;
}
}
return res;
}
}
| 2,550 | 0.44902 | 0.411373 | 98 | 25.020409 | 23.533728 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.459184 | false | false | 13 |
000e762daec4af45cbf2e8248c2e644b238fe31e | 37,606,733,669,682 | 6f672fb72caedccb841ee23f53e32aceeaf1895e | /domioz-source/src/com/dominos/android/sdk/core/user/UserProfileManager$CreditCardErrorType.java | d0c67c8b9cd6399ab4cfcb165f254ff5e845b403 | []
| 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 com.dominos.android.sdk.core.user;
public final class extends Enum
{
private static final GENERAL_CREDIT_CARD_ERROR $VALUES[];
public static final GENERAL_CREDIT_CARD_ERROR CARD_ON_FILE_LIMIT_EXCEEDED;
public static final GENERAL_CREDIT_CARD_ERROR DUPLICATE_NICKNAME;
public static final GENERAL_CREDIT_CARD_ERROR GENERAL_CREDIT_CARD_ERROR;
public static final GENERAL_CREDIT_CARD_ERROR GET_CARD_LIST_ERROR;
public static valueOf(String s)
{
return ()Enum.valueOf(com/dominos/android/sdk/core/user/UserProfileManager$CreditCardErrorType, s);
}
public static [] values()
{
return ([])$VALUES.clone();
}
static
{
DUPLICATE_NICKNAME = new <init>("DUPLICATE_NICKNAME", 0);
GET_CARD_LIST_ERROR = new <init>("GET_CARD_LIST_ERROR", 1);
CARD_ON_FILE_LIMIT_EXCEEDED = new <init>("CARD_ON_FILE_LIMIT_EXCEEDED", 2);
GENERAL_CREDIT_CARD_ERROR = new <init>("GENERAL_CREDIT_CARD_ERROR", 3);
$VALUES = (new .VALUES[] {
DUPLICATE_NICKNAME, GET_CARD_LIST_ERROR, CARD_ON_FILE_LIMIT_EXCEEDED, GENERAL_CREDIT_CARD_ERROR
});
}
private (String s, int i)
{
super(s, i);
}
}
| UTF-8 | Java | 1,396 | java | UserProfileManager$CreditCardErrorType.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.9995900392532349,
"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 com.dominos.android.sdk.core.user;
public final class extends Enum
{
private static final GENERAL_CREDIT_CARD_ERROR $VALUES[];
public static final GENERAL_CREDIT_CARD_ERROR CARD_ON_FILE_LIMIT_EXCEEDED;
public static final GENERAL_CREDIT_CARD_ERROR DUPLICATE_NICKNAME;
public static final GENERAL_CREDIT_CARD_ERROR GENERAL_CREDIT_CARD_ERROR;
public static final GENERAL_CREDIT_CARD_ERROR GET_CARD_LIST_ERROR;
public static valueOf(String s)
{
return ()Enum.valueOf(com/dominos/android/sdk/core/user/UserProfileManager$CreditCardErrorType, s);
}
public static [] values()
{
return ([])$VALUES.clone();
}
static
{
DUPLICATE_NICKNAME = new <init>("DUPLICATE_NICKNAME", 0);
GET_CARD_LIST_ERROR = new <init>("GET_CARD_LIST_ERROR", 1);
CARD_ON_FILE_LIMIT_EXCEEDED = new <init>("CARD_ON_FILE_LIMIT_EXCEEDED", 2);
GENERAL_CREDIT_CARD_ERROR = new <init>("GENERAL_CREDIT_CARD_ERROR", 3);
$VALUES = (new .VALUES[] {
DUPLICATE_NICKNAME, GET_CARD_LIST_ERROR, CARD_ON_FILE_LIMIT_EXCEEDED, GENERAL_CREDIT_CARD_ERROR
});
}
private (String s, int i)
{
super(s, i);
}
}
| 1,386 | 0.666189 | 0.658309 | 42 | 32.238094 | 32.776886 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false | 13 |
09d1ed39efadbb09ca3539e25abce45c97a0a3d4 | 4,844,723,162,236 | ab04355250c5427a6b7cbe6cb72468b4c82ebd3e | /app/src/main/java/com/example/agileproject/ControlView/Contact.java | 5e0eb4ce959c44d2eb9e2cd48aaf333ece5b4871 | []
| no_license | eliajo/COBOL | https://github.com/eliajo/COBOL | 9ec5be195ad99ebc351c18e7c3331857be1162cd | 72b89b95b3784fbf5d4842a1f314f7943162bf54 | refs/heads/master | 2023-05-07T19:18:45.149000 | 2021-06-04T13:30:41 | 2021-06-04T13:30:41 | 351,075,258 | 0 | 0 | null | false | 2021-03-25T09:25:09 | 2021-03-24T12:41:10 | 2021-03-25T09:23:08 | 2021-03-25T09:25:08 | 0 | 0 | 0 | 0 | null | false | false | package com.example.agileproject.ControlView;
import com.example.agileproject.Model.Storable;
/**
* Class for defining how to construct contacts in other classes.
*
* @author Elin Berthag, Alva Leufstedt, Klara Jakobsson
*/
public class Contact {
//A contact consist of a name and one or two ways of contact (phone number and/or email).
String name;
String contactWay;
String optionalContactWay;
//Constructor for new contacts with one way of contacting.
public Contact(String name, String contactWay){
this.name = name;
this.contactWay = contactWay;
}
//Constructor for new contacts with two ways of contacting.
public Contact(String name, String contactWay, String optionalContactWay){
this.name = name;
this.contactWay = contactWay;
this.optionalContactWay = optionalContactWay;
}
public String getInfoToWrite(){
if (optionalContactWay!=null){
return name + "###---###---###" + contactWay + "###---###---###" + optionalContactWay;
}
else {
return name + "###---###---###" + contactWay;
}
}
}
| UTF-8 | Java | 1,151 | java | Contact.java | Java | [
{
"context": "onstruct contacts in other classes.\n *\n * @author Elin Berthag, Alva Leufstedt, Klara Jakobsson\n */\npublic class",
"end": 194,
"score": 0.999886155128479,
"start": 182,
"tag": "NAME",
"value": "Elin Berthag"
},
{
"context": "cts in other classes.\n *\n * @author Elin Berthag, Alva Leufstedt, Klara Jakobsson\n */\npublic class Contact {\n ",
"end": 210,
"score": 0.999872088432312,
"start": 196,
"tag": "NAME",
"value": "Alva Leufstedt"
},
{
"context": "sses.\n *\n * @author Elin Berthag, Alva Leufstedt, Klara Jakobsson\n */\npublic class Contact {\n //A contact consi",
"end": 227,
"score": 0.9998766183853149,
"start": 212,
"tag": "NAME",
"value": "Klara Jakobsson"
}
]
| null | []
| package com.example.agileproject.ControlView;
import com.example.agileproject.Model.Storable;
/**
* Class for defining how to construct contacts in other classes.
*
* @author <NAME>, <NAME>, <NAME>
*/
public class Contact {
//A contact consist of a name and one or two ways of contact (phone number and/or email).
String name;
String contactWay;
String optionalContactWay;
//Constructor for new contacts with one way of contacting.
public Contact(String name, String contactWay){
this.name = name;
this.contactWay = contactWay;
}
//Constructor for new contacts with two ways of contacting.
public Contact(String name, String contactWay, String optionalContactWay){
this.name = name;
this.contactWay = contactWay;
this.optionalContactWay = optionalContactWay;
}
public String getInfoToWrite(){
if (optionalContactWay!=null){
return name + "###---###---###" + contactWay + "###---###---###" + optionalContactWay;
}
else {
return name + "###---###---###" + contactWay;
}
}
}
| 1,128 | 0.636838 | 0.636838 | 37 | 30.108109 | 27.699921 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.459459 | false | false | 13 |
a4cf2795fa77fe42ed7ab746f3834e51ccb59265 | 33,801,392,678,264 | 06aee53cc04adc5bd6bcda1e1e717957b24e4437 | /api/src/main/java/org/accula/api/handlers/GithubWebhookHandler.java | e687d3800e1ea9c2545f583c9f295e30e5250cd8 | []
| no_license | lapter57/accula | https://github.com/lapter57/accula | 9fb4cc62e21b4d3a7e73141a745b57ae40be8d9d | 5456ed9a8b5162933e7c8a121ea4d163f89385a7 | refs/heads/master | 2022-12-16T16:24:27.702000 | 2020-06-13T12:00:07 | 2020-06-13T12:00:07 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.accula.api.handlers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.accula.api.code.CodeLoader;
import org.accula.api.code.FileFilter;
import org.accula.api.db.model.Clone;
import org.accula.api.db.model.Pull;
import org.accula.api.db.repo.CloneRepo;
import org.accula.api.db.repo.ProjectRepo;
import org.accula.api.db.repo.PullRepo;
import org.accula.api.detector.CloneDetector;
import org.accula.api.detector.CodeSnippet;
import org.accula.api.github.model.GithubApiHookPayload;
import org.accula.api.handlers.util.ProjectUpdater;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Scheduler;
import reactor.core.scheduler.Schedulers;
import reactor.util.function.Tuple2;
/**
* @author Anton Lamtev
* @author Vadim Dyachkov
*/
@Component
@Slf4j
@RequiredArgsConstructor
public final class GithubWebhookHandler {
private static final String GITHUB_EVENT = "X-GitHub-Event";
private static final String GITHUB_EVENT_PING = "ping";
private final Scheduler processingScheduler = Schedulers.boundedElastic();
private final ProjectRepo projectRepo;
private final ProjectUpdater projectUpdater;
private final PullRepo pullRepo;
private final CloneRepo cloneRepo;
private final CloneDetector detector;
private final CodeLoader loader;
public Mono<ServerResponse> webhook(final ServerRequest request) {
if (GITHUB_EVENT_PING.equals(request.headers().firstHeader(GITHUB_EVENT))) {
return ServerResponse.ok().build();
}
// TODO: validate signature in X-Hub-Signature
return request
.bodyToMono(GithubApiHookPayload.class)
.flatMap(this::processPayload)
.onErrorResume(e -> {
log.error("Error during payload processing: ", e);
return Mono.empty();
})
.flatMap(p -> ServerResponse.ok().build());
}
public Mono<Void> processPayload(final GithubApiHookPayload payload) {
final var githubApiPull = payload.getPull();
final var savedPull = projectRepo
.idByRepoId(payload.getRepo().getId())
.flatMap(projectId -> projectUpdater.update(projectId, githubApiPull))
.cache();
final var targetFiles = savedPull
.map(Pull::getHead)
.flatMapMany(head -> loader.getFiles(head, FileFilter.JAVA));
final var sourceFiles = savedPull
.flatMapMany(pull -> pullRepo.findUpdatedEarlierThan(pull.getProjectId(), pull.getNumber()))
.map(Pull::getHead)
.flatMap(head -> loader.getFiles(head, FileFilter.JAVA))
.cache();
final var cloneFlux = detector
.findClones(targetFiles, sourceFiles)
.map(this::convert);
final var saveClones = cloneFlux.collectList()
.flatMap(clones -> cloneRepo.insert(clones).then());
return Mono.when(savedPull, saveClones);
}
private Clone convert(final Tuple2<CodeSnippet, CodeSnippet> clone) {
final CodeSnippet target = clone.getT1();
final CodeSnippet source = clone.getT2();
return Clone.builder()
.targetSnapshot(target.getCommitSnapshot())
.targetFile(target.getFile())
.targetFromLine(target.getFromLine())
.targetToLine(target.getToLine())
.sourceSnapshot(source.getCommitSnapshot())
.sourceFile(source.getFile())
.sourceFromLine(source.getFromLine())
.sourceToLine(source.getToLine())
.build();
}
}
| UTF-8 | Java | 3,916 | java | GithubWebhookHandler.java | Java | [
{
"context": "port reactor.util.function.Tuple2;\n\n/**\n * @author Anton Lamtev\n * @author Vadim Dyachkov\n */\n@Component\n@Slf4j\n@",
"end": 959,
"score": 0.999847412109375,
"start": 947,
"tag": "NAME",
"value": "Anton Lamtev"
},
{
"context": "on.Tuple2;\n\n/**\n * @author Anton Lamtev\n * @author Vadim Dyachkov\n */\n@Component\n@Slf4j\n@RequiredArgsConstructor\npu",
"end": 985,
"score": 0.9998365640640259,
"start": 971,
"tag": "NAME",
"value": "Vadim Dyachkov"
}
]
| null | []
| package org.accula.api.handlers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.accula.api.code.CodeLoader;
import org.accula.api.code.FileFilter;
import org.accula.api.db.model.Clone;
import org.accula.api.db.model.Pull;
import org.accula.api.db.repo.CloneRepo;
import org.accula.api.db.repo.ProjectRepo;
import org.accula.api.db.repo.PullRepo;
import org.accula.api.detector.CloneDetector;
import org.accula.api.detector.CodeSnippet;
import org.accula.api.github.model.GithubApiHookPayload;
import org.accula.api.handlers.util.ProjectUpdater;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Scheduler;
import reactor.core.scheduler.Schedulers;
import reactor.util.function.Tuple2;
/**
* @author <NAME>
* @author <NAME>
*/
@Component
@Slf4j
@RequiredArgsConstructor
public final class GithubWebhookHandler {
private static final String GITHUB_EVENT = "X-GitHub-Event";
private static final String GITHUB_EVENT_PING = "ping";
private final Scheduler processingScheduler = Schedulers.boundedElastic();
private final ProjectRepo projectRepo;
private final ProjectUpdater projectUpdater;
private final PullRepo pullRepo;
private final CloneRepo cloneRepo;
private final CloneDetector detector;
private final CodeLoader loader;
public Mono<ServerResponse> webhook(final ServerRequest request) {
if (GITHUB_EVENT_PING.equals(request.headers().firstHeader(GITHUB_EVENT))) {
return ServerResponse.ok().build();
}
// TODO: validate signature in X-Hub-Signature
return request
.bodyToMono(GithubApiHookPayload.class)
.flatMap(this::processPayload)
.onErrorResume(e -> {
log.error("Error during payload processing: ", e);
return Mono.empty();
})
.flatMap(p -> ServerResponse.ok().build());
}
public Mono<Void> processPayload(final GithubApiHookPayload payload) {
final var githubApiPull = payload.getPull();
final var savedPull = projectRepo
.idByRepoId(payload.getRepo().getId())
.flatMap(projectId -> projectUpdater.update(projectId, githubApiPull))
.cache();
final var targetFiles = savedPull
.map(Pull::getHead)
.flatMapMany(head -> loader.getFiles(head, FileFilter.JAVA));
final var sourceFiles = savedPull
.flatMapMany(pull -> pullRepo.findUpdatedEarlierThan(pull.getProjectId(), pull.getNumber()))
.map(Pull::getHead)
.flatMap(head -> loader.getFiles(head, FileFilter.JAVA))
.cache();
final var cloneFlux = detector
.findClones(targetFiles, sourceFiles)
.map(this::convert);
final var saveClones = cloneFlux.collectList()
.flatMap(clones -> cloneRepo.insert(clones).then());
return Mono.when(savedPull, saveClones);
}
private Clone convert(final Tuple2<CodeSnippet, CodeSnippet> clone) {
final CodeSnippet target = clone.getT1();
final CodeSnippet source = clone.getT2();
return Clone.builder()
.targetSnapshot(target.getCommitSnapshot())
.targetFile(target.getFile())
.targetFromLine(target.getFromLine())
.targetToLine(target.getToLine())
.sourceSnapshot(source.getCommitSnapshot())
.sourceFile(source.getFile())
.sourceFromLine(source.getFromLine())
.sourceToLine(source.getToLine())
.build();
}
}
| 3,902 | 0.667007 | 0.66522 | 100 | 38.16 | 23.726238 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.52 | false | false | 13 |
f4fd4304775db8865aea2499ac8caad3a030071f | 11,381,663,403,590 | 28e58422f508f1932f175843926216c825d8e754 | /src/main/java/com/ace/springjdbcdemo/vo/PhoneResponse.java | 60ff4c9c6cf4527c31f9fcf3da56e02181f5c00f | []
| no_license | nilesh44/springjdbcdemo | https://github.com/nilesh44/springjdbcdemo | 0f351982efe7fbbedf9ac3232d4a89f90475df64 | 11cea69cef1051dbb5aae6bee06ba0b4ee6f930e | refs/heads/master | 2023-08-26T07:23:01.536000 | 2021-11-04T09:53:52 | 2021-11-04T09:53:52 | 418,478,142 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ace.springjdbcdemo.vo;
import java.sql.Timestamp;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Builder
@Data
@NoArgsConstructor
@AllArgsConstructor
public class PhoneResponse {
private String phoneId;
private String phoneNumber;
private boolean prefered;
private Timestamp createTimestamp;
private Timestamp expireTimeStamp;
}
| UTF-8 | Java | 413 | java | PhoneResponse.java | Java | []
| null | []
| package com.ace.springjdbcdemo.vo;
import java.sql.Timestamp;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Builder
@Data
@NoArgsConstructor
@AllArgsConstructor
public class PhoneResponse {
private String phoneId;
private String phoneNumber;
private boolean prefered;
private Timestamp createTimestamp;
private Timestamp expireTimeStamp;
}
| 413 | 0.830508 | 0.830508 | 20 | 19.65 | 12.475075 | 35 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.8 | false | false | 13 |
31f92b130b92805bf8971118a993ed5ddc8dc83d | 11,381,663,399,989 | 71a9ccce629c957bb22ef4504fe1413b102f678a | /src/main/java/me/minei/leetcode/problem/Q169.java | 41bdf54d9fe858bc7422d82879bb6b8c85643d7a | []
| no_license | lostars/leetcode-solution | https://github.com/lostars/leetcode-solution | 1f100666cba16926265879e112b9f6a1227eea43 | ca21e552fefcd1f949c8cf28a7697a291c013606 | refs/heads/master | 2023-03-27T03:58:50.200000 | 2021-03-23T07:10:01 | 2021-03-23T07:10:01 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package me.minei.leetcode.problem;
import java.util.Arrays;
/**
* https://leetcode.com/problems/majority-element/description/
*/
public class Q169 {
public static void main(String[] args) {
System.out.println(new Q169().majorityElement2(new int[]{6,5,5,5,6,6,6}));
}
public int majorityElement2(int[] nums) {
// 超过一半 剩下的肯定是答案
int num = nums[0], time = 1;
for (int i = 1; i < nums.length; i++) {
if (time == 0) num = nums[i];
if (nums[i] == num) time++;
else time--;
}
return num;
}
public int majorityElement(int[] nums) {
Arrays.sort(nums);
int num = nums[0];
int time = 0;
for (int n : nums) {
if (n != num) {
if (time > nums.length / 2) {
return num;
} else {
num = n; time = 1;
}
} else {
time++;
}
}
return num;
}
}
| UTF-8 | Java | 1,047 | java | Q169.java | Java | []
| null | []
| package me.minei.leetcode.problem;
import java.util.Arrays;
/**
* https://leetcode.com/problems/majority-element/description/
*/
public class Q169 {
public static void main(String[] args) {
System.out.println(new Q169().majorityElement2(new int[]{6,5,5,5,6,6,6}));
}
public int majorityElement2(int[] nums) {
// 超过一半 剩下的肯定是答案
int num = nums[0], time = 1;
for (int i = 1; i < nums.length; i++) {
if (time == 0) num = nums[i];
if (nums[i] == num) time++;
else time--;
}
return num;
}
public int majorityElement(int[] nums) {
Arrays.sort(nums);
int num = nums[0];
int time = 0;
for (int n : nums) {
if (n != num) {
if (time > nums.length / 2) {
return num;
} else {
num = n; time = 1;
}
} else {
time++;
}
}
return num;
}
}
| 1,047 | 0.44868 | 0.426197 | 41 | 23.95122 | 18.195351 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.609756 | false | false | 13 |
f4f983af03fb19744394fa81d3830e4f20009a8e | 970,662,670,962 | 4e81eaa4aebd17f743ff6d1c216070dfafbf1341 | /Dart/src/com/jetbrains/lang/dart/ide/generation/DartGenerateAccessorHandler.java | 97c195321b854ffee8d70ff2f34dd2039ff34ef4 | [
"Apache-2.0"
]
| permissive | tivenwang/intellij-plugins | https://github.com/tivenwang/intellij-plugins | 18a64d36c34401712d5f3e7c7a731e929ea8038f | 58c6e77ec112c0cd8973531c2d02961e9d765461 | refs/heads/master | 2020-12-03T03:32:00.240000 | 2016-01-12T11:09:10 | 2016-01-12T11:11:20 | 49,498,940 | 2 | 0 | null | true | 2016-01-12T12:32:54 | 2016-01-12T12:32:53 | 2016-01-11T23:54:52 | 2016-01-12T12:00:42 | 286,247 | 0 | 0 | 0 | null | null | null | package com.jetbrains.lang.dart.ide.generation;
import com.intellij.openapi.util.Pair;
import com.jetbrains.lang.dart.DartComponentType;
import com.jetbrains.lang.dart.psi.DartClass;
import com.jetbrains.lang.dart.psi.DartComponent;
import com.jetbrains.lang.dart.util.DartResolveUtil;
import java.util.List;
import java.util.Map;
/**
* @author: Fedor.Korotkov
*/
public abstract class DartGenerateAccessorHandler extends BaseDartGenerateHandler {
private final CreateGetterSetterFix.Strategy myStrategy;
protected DartGenerateAccessorHandler(CreateGetterSetterFix.Strategy strategy) {
myStrategy = strategy;
}
@Override
protected BaseCreateMethodsFix createFix(DartClass dartClass) {
return new CreateGetterSetterFix(dartClass, myStrategy);
}
@Override
protected void collectCandidates(DartClass dartClass, List<DartComponent> candidates) {
final List<DartComponent> subComponents = DartResolveUtil.getNamedSubComponents(dartClass);
for (DartComponent dartComponent : subComponents) {
if (DartComponentType.typeOf(dartComponent) != DartComponentType.FIELD) continue;
if (dartComponent.isStatic()) continue;
if (!myStrategy.accept(dartComponent.getName(), subComponents)) continue;
candidates.add(dartComponent);
}
}
@Override
protected void collectCandidates(Map<Pair<String, Boolean>, DartComponent> classMembersMap,
Map<Pair<String, Boolean>, DartComponent> superClassesMembersMap,
Map<Pair<String, Boolean>, DartComponent> superInterfacesMembersMap,
List<DartComponent> candidates) {
// ignore
}
}
| UTF-8 | Java | 1,692 | java | DartGenerateAccessorHandler.java | Java | [
{
"context": ".util.List;\nimport java.util.Map;\n\n/**\n * @author: Fedor.Korotkov\n */\npublic abstract class DartGenerateAccessorHan",
"end": 364,
"score": 0.9998172521591187,
"start": 350,
"tag": "NAME",
"value": "Fedor.Korotkov"
}
]
| null | []
| package com.jetbrains.lang.dart.ide.generation;
import com.intellij.openapi.util.Pair;
import com.jetbrains.lang.dart.DartComponentType;
import com.jetbrains.lang.dart.psi.DartClass;
import com.jetbrains.lang.dart.psi.DartComponent;
import com.jetbrains.lang.dart.util.DartResolveUtil;
import java.util.List;
import java.util.Map;
/**
* @author: Fedor.Korotkov
*/
public abstract class DartGenerateAccessorHandler extends BaseDartGenerateHandler {
private final CreateGetterSetterFix.Strategy myStrategy;
protected DartGenerateAccessorHandler(CreateGetterSetterFix.Strategy strategy) {
myStrategy = strategy;
}
@Override
protected BaseCreateMethodsFix createFix(DartClass dartClass) {
return new CreateGetterSetterFix(dartClass, myStrategy);
}
@Override
protected void collectCandidates(DartClass dartClass, List<DartComponent> candidates) {
final List<DartComponent> subComponents = DartResolveUtil.getNamedSubComponents(dartClass);
for (DartComponent dartComponent : subComponents) {
if (DartComponentType.typeOf(dartComponent) != DartComponentType.FIELD) continue;
if (dartComponent.isStatic()) continue;
if (!myStrategy.accept(dartComponent.getName(), subComponents)) continue;
candidates.add(dartComponent);
}
}
@Override
protected void collectCandidates(Map<Pair<String, Boolean>, DartComponent> classMembersMap,
Map<Pair<String, Boolean>, DartComponent> superClassesMembersMap,
Map<Pair<String, Boolean>, DartComponent> superInterfacesMembersMap,
List<DartComponent> candidates) {
// ignore
}
}
| 1,692 | 0.736407 | 0.736407 | 49 | 33.530613 | 34.037254 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false | 13 |
eea6d61dde4749fa7bb31720dd735c69300ce540 | 39,462,159,546,395 | 98c83d8da341764f4b343598f58705d198b047e7 | /src/main/java/infrastructure/maptoRevxProject/RevXProjectService.java | b79bf91ef7d039b9a41c5fb98f7d3a89b072c551 | []
| no_license | lorenzoMacca/Revx | https://github.com/lorenzoMacca/Revx | 74dee9fecfb603a67bb6ecb882a007c15bb81be6 | 1e6010ae82a4e28c2dccfca6b599fc10b4430531 | refs/heads/main | 2023-08-22T10:10:02.512000 | 2020-12-18T13:52:58 | 2020-12-18T13:52:58 | 322,607,445 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package infrastructure.maptoRevxProject;
import application.IRevXProjectService;
import domain.ProjectRoot;
import domain.RevXPackage;
import domain.RevXProject;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.stream.Stream;
public class RevXProjectService implements IRevXProjectService {
@Override
public RevXProject create(String name, ProjectRoot projectRoot) {
validatePath(projectRoot);
RevXProject revXProject = new RevXProject(name);
revXProject = mapExternalStructureToRevXProject(revXProject, projectRoot);
return revXProject;
}
private RevXProject mapExternalStructureToRevXProject(RevXProject revXProject, ProjectRoot projectRoot) {
try (Stream<Path> walk = Files.walk(Path.of(projectRoot.getPath()))) {
walk.filter(Files::isDirectory)
.forEach(directory -> revXProject.addPackage(new RevXPackage(directory.toAbsolutePath().toString())));
} catch (IOException e) {
e.printStackTrace();
}
return revXProject;
}
private void validatePath(ProjectRoot projectRoot) {
if(! Files.exists(Path.of(projectRoot.getPath()))){
throw new RuntimeException("Path does not exists: " + projectRoot.getPath());
}
}
}
| UTF-8 | Java | 1,341 | java | RevXProjectService.java | Java | []
| null | []
| package infrastructure.maptoRevxProject;
import application.IRevXProjectService;
import domain.ProjectRoot;
import domain.RevXPackage;
import domain.RevXProject;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.stream.Stream;
public class RevXProjectService implements IRevXProjectService {
@Override
public RevXProject create(String name, ProjectRoot projectRoot) {
validatePath(projectRoot);
RevXProject revXProject = new RevXProject(name);
revXProject = mapExternalStructureToRevXProject(revXProject, projectRoot);
return revXProject;
}
private RevXProject mapExternalStructureToRevXProject(RevXProject revXProject, ProjectRoot projectRoot) {
try (Stream<Path> walk = Files.walk(Path.of(projectRoot.getPath()))) {
walk.filter(Files::isDirectory)
.forEach(directory -> revXProject.addPackage(new RevXPackage(directory.toAbsolutePath().toString())));
} catch (IOException e) {
e.printStackTrace();
}
return revXProject;
}
private void validatePath(ProjectRoot projectRoot) {
if(! Files.exists(Path.of(projectRoot.getPath()))){
throw new RuntimeException("Path does not exists: " + projectRoot.getPath());
}
}
}
| 1,341 | 0.704698 | 0.704698 | 50 | 25.82 | 30.67161 | 118 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false | 13 |
ecc59ef0f80814eee23856860733222a6888c3c7 | 21,998,822,554,176 | e692465c4e59d0eae59ba10d828720d7c4d56ce7 | /src/main/java/com/jobori/kpmg/callenge/two/Huffman.java | f37fd0fd26159d661e7d65755391c4c6686f139a | []
| no_license | borijani/Challenge | https://github.com/borijani/Challenge | 951c1b9d8cc347040e94f49c3abd252c4e8975cb | 487864fe1eedfcf0624736a6a935274f08740f3f | refs/heads/master | 2021-01-10T14:19:28.028000 | 2016-02-24T12:26:09 | 2016-02-24T12:26:09 | 52,363,762 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.jobori.kpmg.callenge.two;
import com.sun.javaws.exceptions.InvalidArgumentException;
import java.util.*;
import java.util.stream.Collectors;
/**
* Created by Janos on 24/02/2016.
*/
public class Huffman {
final static class Node {
private char character;
private int frequency;
private Node left;
private Node right;
private Node(char character, int frequency, Node left, Node right) {
this.character = character;
this.frequency = frequency;
this.left = left;
this.right = right;
}
@Override
public String toString() {
StringBuilder result = new StringBuilder();
convertToString(this, "", result);
return result.toString();
}
public void convertToString(Node node, String tab, StringBuilder result) {
if (node.left != null || node.right != null) {
convertToString(node.left, tab + "0", result);
convertToString(node.right, tab + "1", result);
} else {
result.append(node.character).append(' ').append(node.frequency).append(' ').append(tab).append('\n');
}
}
}
public static void main(String[] args) {
Huffman huffman = new Huffman();
Node root = huffman.buildTree(args[0]);
System.out.println(root);
}
public Node buildTree(String input) {
if (input == null || input.isEmpty()) throw new IllegalArgumentException();
Map<Character, Integer> frequencyMap = input.chars().boxed().collect(Collectors.groupingBy(i -> (char) i.intValue(), Collectors.reducing(0, e -> 1, Integer::sum)));
PriorityQueue<Node> orderedFrequencies = frequencyMap.entrySet().stream().map(e -> new Node(e.getKey(), e.getValue(), null, null)).collect(Collectors.toCollection(() -> new PriorityQueue<>(
(n1, n2) -> n1.frequency - n2.frequency)
)
);
return buildTree(orderedFrequencies);
}
private static Node buildTree(PriorityQueue<Node> orderedFrequencies) {
while (orderedFrequencies.size() > 1) {
final Node node1 = orderedFrequencies.remove();
final Node node2 = orderedFrequencies.remove();
Node node = new Node('*', node1.frequency + node2.frequency, node1, node2);
orderedFrequencies.add(node);
}
return orderedFrequencies.remove();
}
}
| UTF-8 | Java | 2,507 | java | Huffman.java | Java | [
{
"context": "rt java.util.stream.Collectors;\n\n/**\n * Created by Janos on 24/02/2016.\n */\npublic class Huffman {\n\n fi",
"end": 179,
"score": 0.9469033479690552,
"start": 174,
"tag": "NAME",
"value": "Janos"
}
]
| null | []
| package com.jobori.kpmg.callenge.two;
import com.sun.javaws.exceptions.InvalidArgumentException;
import java.util.*;
import java.util.stream.Collectors;
/**
* Created by Janos on 24/02/2016.
*/
public class Huffman {
final static class Node {
private char character;
private int frequency;
private Node left;
private Node right;
private Node(char character, int frequency, Node left, Node right) {
this.character = character;
this.frequency = frequency;
this.left = left;
this.right = right;
}
@Override
public String toString() {
StringBuilder result = new StringBuilder();
convertToString(this, "", result);
return result.toString();
}
public void convertToString(Node node, String tab, StringBuilder result) {
if (node.left != null || node.right != null) {
convertToString(node.left, tab + "0", result);
convertToString(node.right, tab + "1", result);
} else {
result.append(node.character).append(' ').append(node.frequency).append(' ').append(tab).append('\n');
}
}
}
public static void main(String[] args) {
Huffman huffman = new Huffman();
Node root = huffman.buildTree(args[0]);
System.out.println(root);
}
public Node buildTree(String input) {
if (input == null || input.isEmpty()) throw new IllegalArgumentException();
Map<Character, Integer> frequencyMap = input.chars().boxed().collect(Collectors.groupingBy(i -> (char) i.intValue(), Collectors.reducing(0, e -> 1, Integer::sum)));
PriorityQueue<Node> orderedFrequencies = frequencyMap.entrySet().stream().map(e -> new Node(e.getKey(), e.getValue(), null, null)).collect(Collectors.toCollection(() -> new PriorityQueue<>(
(n1, n2) -> n1.frequency - n2.frequency)
)
);
return buildTree(orderedFrequencies);
}
private static Node buildTree(PriorityQueue<Node> orderedFrequencies) {
while (orderedFrequencies.size() > 1) {
final Node node1 = orderedFrequencies.remove();
final Node node2 = orderedFrequencies.remove();
Node node = new Node('*', node1.frequency + node2.frequency, node1, node2);
orderedFrequencies.add(node);
}
return orderedFrequencies.remove();
}
}
| 2,507 | 0.598325 | 0.588751 | 73 | 33.342464 | 36.737579 | 197 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.767123 | false | false | 13 |
851e7558b55349956d86b407ae267a8889b76608 | 36,026,185,719,899 | 1c927849b4e25ec726bf29458b1c2483e9b42622 | /src/main/java/com/whosly/infra/exportx/metadata/api/IDataModel.java | db2829e2d296659a4b58369e125b92330f4893bd | [
"Apache-2.0"
]
| permissive | yueny/exportx | https://github.com/yueny/exportx | 7419f1c176d47f7c1e13b4cece46b462d5c392f1 | d1fa53b5b792435ce9f3a37f4c9fd902f8155828 | refs/heads/main | 2023-01-27T16:04:51.518000 | 2020-12-10T15:23:37 | 2020-12-10T15:23:37 | 320,285,729 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.whosly.infra.exportx.metadata.api;
/**
* 改类中的所有 field, 均会输出
*/
public interface IDataModel {
//.
}
| UTF-8 | Java | 138 | java | IDataModel.java | Java | []
| null | []
| package com.whosly.infra.exportx.metadata.api;
/**
* 改类中的所有 field, 均会输出
*/
public interface IDataModel {
//.
}
| 138 | 0.669492 | 0.669492 | 8 | 13.75 | 15.6265 | 46 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 13 |
8a35dc5b8072113b2262938f381742f24c9b8ea3 | 35,029,753,320,378 | 9a4980a3122937d498f68e6b3e7bcc8e03be8f38 | /OhmsLaw.java | 4f25bcc93155ecbe7f415d7ba3bdf7dfb3be2532 | []
| no_license | SebastianHoer/Units-Java | https://github.com/SebastianHoer/Units-Java | 9d466259ffa01bee24be96977a4f489d10d39e0b | 6952a6cde53f91f9cdac1992df413f55dfb293b5 | refs/heads/master | 2020-01-23T21:57:09.944000 | 2016-11-25T04:37:32 | 2016-11-25T04:37:32 | 74,725,902 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.sebastianjhoer.ohmslawcal;
import android.util.Log;
import java.text.DecimalFormat;
/**
* Created by Sebastian on 4/4/2016.
*/
public class OhmsLaw {
//enum for units used mainly for working with user inputs and display not intended for calculation
public enum Units{
//Terra(1.0E12,'T',"Terra","(?:\\d*\\.)?\\d+\\.?[T]"), //Long 1,000,000,000,000 TO Long for double
Giga(1.0E9,'G',"Giga","(?:\\d*\\.)?\\d+\\.?[G]"), // 1,000,000,000
Mega(1.0E6,'M',"Mega","(?:\\d*\\.)?\\d+\\.?[M]"),// 1,000,000
kilo(1.0E3,'k',"kilo","(?:\\d*\\.)?\\d+\\.?[k]"),//1,000
none(1,'X'," ","(?:\\d*\\.)?\\d+"), //100
milli(1.0E-3,'m',"milli","(?:\\d*\\.)?\\d+\\.?[m]"),//.001
micro(1.0E-6,'u',"micro","(?:\\d*\\.)?\\d+\\.?[u]"),//.000001
nano(1.0E-9,'n',"nano","(?:\\d*\\.)?\\d+\\.?[n]");//.000000001
//pico(1.0E-12,'p',"pico","(?:\\d*\\.)?\\d+\\.?[p]");//.0000000001 just to small to be any use
//\d+(?:\.\d+)?(?=\s*(T|G|M|k|m|u|n|p|Giga|Mega|kilo|milli|micro|nano))
private final double value;
private final char symbol;
private final String UnitName;
private final String Regex;
Units(double value, char symbol, String UnitName,String Regex){
this.value = value;
this.symbol = symbol;
this.UnitName = UnitName;
this.Regex = Regex;
}
//UnitsApply returns a matching unit from a number enum
public static Units getUnit(Double NoUnitNumber){
Units Foo = Units.none;
for(Units cName : Units.values())
if(NoUnitNumber / cName.value <= 999 && NoUnitNumber / cName.value >= 1)
Foo = cName;
return Foo;
}
//finds user intended unit example 12k, 120k, 1.2k finds unit kilo
public static Units getUnitFromString(String YesUnitNumber) {
Log.i( "getUnitFromString", "YesUnitNumber:" + YesUnitNumber);
if (YesUnitNumber.matches("(?:\\d*\\.)?\\d+\\.?[TGMkmunp]?")) {
for (Units cName : Units.values()) {
if (YesUnitNumber.matches(cName.Regex)) {
Log.i("getUnitFromString", "RegEx match:" + cName);
return cName;
}
}
}
else{
Log.e( "getUnitFromString", "Error RegEx no match");}
return null;
}
// Converts a String with a Unit and a Number to a Double example 12.0k to 12000
public static double getdoubleFromString(String YesUnitNumber){
Log.i( "getdoubleFromString", "Pram/YesUnitNumber:" + YesUnitNumber);
double NoUnitNumber = 0.0;
Units unit = getUnitFromString(YesUnitNumber);
if(null == unit){Log.w("getdoubleFromString", "Error null from getUnitFromString" + NoUnitNumber); return NoUnitNumber;}// this catchs getUnitFromString null if regex fails and returns a 0.0.
if(unit == none){Log.i("getdoubleFromString", "return/YesUnitNumber:" + Double.parseDouble(YesUnitNumber) * none.value); return Double.parseDouble(YesUnitNumber)* none.value;}
YesUnitNumber = DeleteLastChar(YesUnitNumber);
if(!YesUnitNumber.matches("(?:\\d*\\.)?\\d+")){return NoUnitNumber;}
NoUnitNumber = Double.parseDouble(YesUnitNumber);
for(Units cName : Units.values()){
if(cName.equals(unit)){
Log.i( "getdoubleFromString", "return/YesUnitNumber:" + NoUnitNumber * cName.value);
return NoUnitNumber * cName.value;
}
}
return NoUnitNumber;
}
//Method to remove the end unit symbol
private static String DeleteLastChar(String YesUnitNumber){
Log.i( "DeleteLastChar", "Pram/YesUnitNumber:" + YesUnitNumber);
return YesUnitNumber.substring(0,YesUnitNumber.length()-1);
/* StringBuilder SB = new StringBuilder(YesUnitNumber);
int IndexOfCharAtLast = SB.length() - 1;
SB.deleteCharAt(IndexOfCharAtLast);
String NoUnitNumber = SB.toString();
Log.i( "DeleteLastChar", "return/NoUnitNumber:" + NoUnitNumber);
return NoUnitNumber;*/
}
// Converts a Double to a String with unit example 12000 to 12.0kilo
public static String getUnitStringFromDouble(double NoUnitNumber){
Log.i( "getUnitStringFromDouble", "Pram/NoUnitNumber:" + NoUnitNumber);
DecimalFormat df = new DecimalFormat("###.###");
String YesUnitNumber;
Units unit = getUnit(NoUnitNumber);
double UnitConvert = NoUnitNumber / unit.value;
String UnitNumber = df.format(UnitConvert); //Double.toString(NoUnitNumber / unit.Factor);
String UnitName = unit.UnitName;
YesUnitNumber = UnitNumber + UnitName;
Log.i( "getUnitStringFromDouble", "return/YesUnitNumber:" + YesUnitNumber);
return YesUnitNumber;
}
//overloaded for Changing decimalformat
public static String getUnitStringFromDouble(double NoUnitNumber,String decimalformat){
Log.i( "getUnitStringFromDouble", "Pram/NoUnitNumber:" + NoUnitNumber);
DecimalFormat df = new DecimalFormat(decimalformat);
String YesUnitNumber;
Units unit = getUnit(NoUnitNumber);
double UnitConvert = NoUnitNumber / unit.value;
String UnitNumber = df.format(UnitConvert); //Double.toString(NoUnitNumber / unit.Factor);
String UnitName = unit.UnitName;
YesUnitNumber = UnitNumber + UnitName;
Log.i( "getUnitStringFromDouble", "return/YesUnitNumber:" + YesUnitNumber);
return YesUnitNumber;
}
}
public enum Formula{
AmpsFrom_Volts_Ohms,
AmpsFrom_Power_Volts,
AmpsFrom_Power_Ohms,
VoltsFrom_Power_Ohms,
VoltsFrom_Power_Amps,
VoltsFrom_Amps_Ohms,
OhmsFrom_Volts_Amps,
OhmsFrom_Volts_Power,
OhmsFrom_Power_Amps,
PowerFrom_Volts_Ohms,
PowerFrom_Amps_Ohms,
PowerFrom_Volts_Amps,
ResonantFrequencyFrom_Henrys_Farads,
ReactanceFrom__Henrys_Hertz,
ReactanceFrom__Farads_Hertz;
public static double FormulaSelect
(Formula Switch_State_Select,double Input_Value_One,double Input_Value_Two){
Log.i( "FormulaSelect", "Pram/Switch_State_Select Input_Value_One Input_Value_Two:" +" "+ Switch_State_Select +" "+ Input_Value_One +" "+Input_Value_Two);
double Answer_From_Switch = 0;
switch(Switch_State_Select){
case AmpsFrom_Volts_Ohms: case AmpsFrom_Power_Volts: case VoltsFrom_Power_Amps: case OhmsFrom_Volts_Amps:
Answer_From_Switch = Input_Value_One / Input_Value_Two;
break;
case AmpsFrom_Power_Ohms:
Input_Value_One /= Input_Value_Two;
Answer_From_Switch = Math.sqrt(Input_Value_One);
break;
case VoltsFrom_Power_Ohms:
Input_Value_One *= Input_Value_Two;
Answer_From_Switch = Math.sqrt(Input_Value_One);
break;
case VoltsFrom_Amps_Ohms: case PowerFrom_Volts_Amps:
Answer_From_Switch = Input_Value_One * Input_Value_Two;
break;
case OhmsFrom_Volts_Power: case PowerFrom_Volts_Ohms:
Input_Value_One = Math.pow(Input_Value_One,2);
Answer_From_Switch = Input_Value_One / Input_Value_Two;
break;
case OhmsFrom_Power_Amps:
Input_Value_Two = Math.pow(Input_Value_Two,2);
Answer_From_Switch = Input_Value_One / Input_Value_Two;
break;
case PowerFrom_Amps_Ohms:
Input_Value_One = Math.pow(Input_Value_One,2);
Answer_From_Switch = Input_Value_One * Input_Value_Two;
break;
case ResonantFrequencyFrom_Henrys_Farads:
Answer_From_Switch = 1 / (2 * Math.PI * Math.sqrt(Input_Value_One * Input_Value_Two));
break;
case ReactanceFrom__Farads_Hertz:
Answer_From_Switch = 1 / (2 * Math.PI *(Input_Value_One * Input_Value_Two));
break;
case ReactanceFrom__Henrys_Hertz:
Answer_From_Switch = 2 * Math.PI *(Input_Value_One * Input_Value_Two);
break;
}
Log.i( "FormulaSelect", "return/Answer_From_Switch:" + Answer_From_Switch);
return Answer_From_Switch;
}
}
}
| UTF-8 | Java | 8,959 | java | OhmsLaw.java | Java | [
{
"context": "package com.sebastianjhoer.ohmslawcal;\n\nimport android.util.Log;\n",
"end": 15,
"score": 0.5671133995056152,
"start": 14,
"tag": "USERNAME",
"value": "b"
},
{
"context": "import java.text.DecimalFormat;\n\n/**\n * Created by Sebastian on 4/4/2016.\n */\npublic class OhmsLaw {\n //enu",
"end": 126,
"score": 0.9997696280479431,
"start": 117,
"tag": "NAME",
"value": "Sebastian"
}
]
| null | []
| package com.sebastianjhoer.ohmslawcal;
import android.util.Log;
import java.text.DecimalFormat;
/**
* Created by Sebastian on 4/4/2016.
*/
public class OhmsLaw {
//enum for units used mainly for working with user inputs and display not intended for calculation
public enum Units{
//Terra(1.0E12,'T',"Terra","(?:\\d*\\.)?\\d+\\.?[T]"), //Long 1,000,000,000,000 TO Long for double
Giga(1.0E9,'G',"Giga","(?:\\d*\\.)?\\d+\\.?[G]"), // 1,000,000,000
Mega(1.0E6,'M',"Mega","(?:\\d*\\.)?\\d+\\.?[M]"),// 1,000,000
kilo(1.0E3,'k',"kilo","(?:\\d*\\.)?\\d+\\.?[k]"),//1,000
none(1,'X'," ","(?:\\d*\\.)?\\d+"), //100
milli(1.0E-3,'m',"milli","(?:\\d*\\.)?\\d+\\.?[m]"),//.001
micro(1.0E-6,'u',"micro","(?:\\d*\\.)?\\d+\\.?[u]"),//.000001
nano(1.0E-9,'n',"nano","(?:\\d*\\.)?\\d+\\.?[n]");//.000000001
//pico(1.0E-12,'p',"pico","(?:\\d*\\.)?\\d+\\.?[p]");//.0000000001 just to small to be any use
//\d+(?:\.\d+)?(?=\s*(T|G|M|k|m|u|n|p|Giga|Mega|kilo|milli|micro|nano))
private final double value;
private final char symbol;
private final String UnitName;
private final String Regex;
Units(double value, char symbol, String UnitName,String Regex){
this.value = value;
this.symbol = symbol;
this.UnitName = UnitName;
this.Regex = Regex;
}
//UnitsApply returns a matching unit from a number enum
public static Units getUnit(Double NoUnitNumber){
Units Foo = Units.none;
for(Units cName : Units.values())
if(NoUnitNumber / cName.value <= 999 && NoUnitNumber / cName.value >= 1)
Foo = cName;
return Foo;
}
//finds user intended unit example 12k, 120k, 1.2k finds unit kilo
public static Units getUnitFromString(String YesUnitNumber) {
Log.i( "getUnitFromString", "YesUnitNumber:" + YesUnitNumber);
if (YesUnitNumber.matches("(?:\\d*\\.)?\\d+\\.?[TGMkmunp]?")) {
for (Units cName : Units.values()) {
if (YesUnitNumber.matches(cName.Regex)) {
Log.i("getUnitFromString", "RegEx match:" + cName);
return cName;
}
}
}
else{
Log.e( "getUnitFromString", "Error RegEx no match");}
return null;
}
// Converts a String with a Unit and a Number to a Double example 12.0k to 12000
public static double getdoubleFromString(String YesUnitNumber){
Log.i( "getdoubleFromString", "Pram/YesUnitNumber:" + YesUnitNumber);
double NoUnitNumber = 0.0;
Units unit = getUnitFromString(YesUnitNumber);
if(null == unit){Log.w("getdoubleFromString", "Error null from getUnitFromString" + NoUnitNumber); return NoUnitNumber;}// this catchs getUnitFromString null if regex fails and returns a 0.0.
if(unit == none){Log.i("getdoubleFromString", "return/YesUnitNumber:" + Double.parseDouble(YesUnitNumber) * none.value); return Double.parseDouble(YesUnitNumber)* none.value;}
YesUnitNumber = DeleteLastChar(YesUnitNumber);
if(!YesUnitNumber.matches("(?:\\d*\\.)?\\d+")){return NoUnitNumber;}
NoUnitNumber = Double.parseDouble(YesUnitNumber);
for(Units cName : Units.values()){
if(cName.equals(unit)){
Log.i( "getdoubleFromString", "return/YesUnitNumber:" + NoUnitNumber * cName.value);
return NoUnitNumber * cName.value;
}
}
return NoUnitNumber;
}
//Method to remove the end unit symbol
private static String DeleteLastChar(String YesUnitNumber){
Log.i( "DeleteLastChar", "Pram/YesUnitNumber:" + YesUnitNumber);
return YesUnitNumber.substring(0,YesUnitNumber.length()-1);
/* StringBuilder SB = new StringBuilder(YesUnitNumber);
int IndexOfCharAtLast = SB.length() - 1;
SB.deleteCharAt(IndexOfCharAtLast);
String NoUnitNumber = SB.toString();
Log.i( "DeleteLastChar", "return/NoUnitNumber:" + NoUnitNumber);
return NoUnitNumber;*/
}
// Converts a Double to a String with unit example 12000 to 12.0kilo
public static String getUnitStringFromDouble(double NoUnitNumber){
Log.i( "getUnitStringFromDouble", "Pram/NoUnitNumber:" + NoUnitNumber);
DecimalFormat df = new DecimalFormat("###.###");
String YesUnitNumber;
Units unit = getUnit(NoUnitNumber);
double UnitConvert = NoUnitNumber / unit.value;
String UnitNumber = df.format(UnitConvert); //Double.toString(NoUnitNumber / unit.Factor);
String UnitName = unit.UnitName;
YesUnitNumber = UnitNumber + UnitName;
Log.i( "getUnitStringFromDouble", "return/YesUnitNumber:" + YesUnitNumber);
return YesUnitNumber;
}
//overloaded for Changing decimalformat
public static String getUnitStringFromDouble(double NoUnitNumber,String decimalformat){
Log.i( "getUnitStringFromDouble", "Pram/NoUnitNumber:" + NoUnitNumber);
DecimalFormat df = new DecimalFormat(decimalformat);
String YesUnitNumber;
Units unit = getUnit(NoUnitNumber);
double UnitConvert = NoUnitNumber / unit.value;
String UnitNumber = df.format(UnitConvert); //Double.toString(NoUnitNumber / unit.Factor);
String UnitName = unit.UnitName;
YesUnitNumber = UnitNumber + UnitName;
Log.i( "getUnitStringFromDouble", "return/YesUnitNumber:" + YesUnitNumber);
return YesUnitNumber;
}
}
public enum Formula{
AmpsFrom_Volts_Ohms,
AmpsFrom_Power_Volts,
AmpsFrom_Power_Ohms,
VoltsFrom_Power_Ohms,
VoltsFrom_Power_Amps,
VoltsFrom_Amps_Ohms,
OhmsFrom_Volts_Amps,
OhmsFrom_Volts_Power,
OhmsFrom_Power_Amps,
PowerFrom_Volts_Ohms,
PowerFrom_Amps_Ohms,
PowerFrom_Volts_Amps,
ResonantFrequencyFrom_Henrys_Farads,
ReactanceFrom__Henrys_Hertz,
ReactanceFrom__Farads_Hertz;
public static double FormulaSelect
(Formula Switch_State_Select,double Input_Value_One,double Input_Value_Two){
Log.i( "FormulaSelect", "Pram/Switch_State_Select Input_Value_One Input_Value_Two:" +" "+ Switch_State_Select +" "+ Input_Value_One +" "+Input_Value_Two);
double Answer_From_Switch = 0;
switch(Switch_State_Select){
case AmpsFrom_Volts_Ohms: case AmpsFrom_Power_Volts: case VoltsFrom_Power_Amps: case OhmsFrom_Volts_Amps:
Answer_From_Switch = Input_Value_One / Input_Value_Two;
break;
case AmpsFrom_Power_Ohms:
Input_Value_One /= Input_Value_Two;
Answer_From_Switch = Math.sqrt(Input_Value_One);
break;
case VoltsFrom_Power_Ohms:
Input_Value_One *= Input_Value_Two;
Answer_From_Switch = Math.sqrt(Input_Value_One);
break;
case VoltsFrom_Amps_Ohms: case PowerFrom_Volts_Amps:
Answer_From_Switch = Input_Value_One * Input_Value_Two;
break;
case OhmsFrom_Volts_Power: case PowerFrom_Volts_Ohms:
Input_Value_One = Math.pow(Input_Value_One,2);
Answer_From_Switch = Input_Value_One / Input_Value_Two;
break;
case OhmsFrom_Power_Amps:
Input_Value_Two = Math.pow(Input_Value_Two,2);
Answer_From_Switch = Input_Value_One / Input_Value_Two;
break;
case PowerFrom_Amps_Ohms:
Input_Value_One = Math.pow(Input_Value_One,2);
Answer_From_Switch = Input_Value_One * Input_Value_Two;
break;
case ResonantFrequencyFrom_Henrys_Farads:
Answer_From_Switch = 1 / (2 * Math.PI * Math.sqrt(Input_Value_One * Input_Value_Two));
break;
case ReactanceFrom__Farads_Hertz:
Answer_From_Switch = 1 / (2 * Math.PI *(Input_Value_One * Input_Value_Two));
break;
case ReactanceFrom__Henrys_Hertz:
Answer_From_Switch = 2 * Math.PI *(Input_Value_One * Input_Value_Two);
break;
}
Log.i( "FormulaSelect", "return/Answer_From_Switch:" + Answer_From_Switch);
return Answer_From_Switch;
}
}
}
| 8,959 | 0.561781 | 0.546043 | 227 | 38.462555 | 35.329937 | 203 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.845815 | false | false | 13 |
74678eb91e688bbfd6bc007434bcb4acd8860dd8 | 35,012,573,451,572 | c874e3e876959960f9318f7adcde99c3ab951969 | /dynamitegc-service/src/main/java/com/dynamitegc/membership/business/GymnastDocumentRepository.java | 51787c935fac8bcbeb5b39ff60b8caefd01e1e61 | []
| no_license | AmericanConsultants/gsa-aeec-pool2-prototype | https://github.com/AmericanConsultants/gsa-aeec-pool2-prototype | 7eb86ba1776a2fa328f8a755a0d44447f1f456a4 | 5830565db59dafb8b4933ae0398344474bfceaf7 | refs/heads/master | 2021-01-22T04:41:51.184000 | 2015-07-07T16:49:22 | 2015-07-07T16:49:22 | 38,697,590 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.dynamitegc.membership.business;
import java.util.List;
import org.springframework.data.solr.repository.Query;
import org.springframework.data.solr.repository.SolrCrudRepository;
/**
* Extend the SolrCrudRepository for our Gymnast.
* @author bsneade
*/
public interface GymnastDocumentRepository extends SolrCrudRepository<GymnastDocument, String>{
/**
* Searches for the term in any of the member fields.
*
* @param searchTerm to search for
* @param tenantId for the record
* @return The list of matches
*/
@Query(value = "(firstName_t:*?0* OR lastName_t:*?0* OR nickname_t:*?0* OR phone_txt:*?0* OR emergencyContactName_txt:*?0* OR emergencyContactPhone_txt:*?0* OR schoolName_t:*?0*) AND tenantId_s:?1",
fields = "id")
List<GymnastDocument> findByAll(String searchTerm, String tenantId);
}
| UTF-8 | Java | 870 | java | GymnastDocumentRepository.java | Java | [
{
"context": "the SolrCrudRepository for our Gymnast.\n * @author bsneade\n */\npublic interface GymnastDocumentRepository ex",
"end": 264,
"score": 0.9995582699775696,
"start": 257,
"tag": "USERNAME",
"value": "bsneade"
}
]
| null | []
| package com.dynamitegc.membership.business;
import java.util.List;
import org.springframework.data.solr.repository.Query;
import org.springframework.data.solr.repository.SolrCrudRepository;
/**
* Extend the SolrCrudRepository for our Gymnast.
* @author bsneade
*/
public interface GymnastDocumentRepository extends SolrCrudRepository<GymnastDocument, String>{
/**
* Searches for the term in any of the member fields.
*
* @param searchTerm to search for
* @param tenantId for the record
* @return The list of matches
*/
@Query(value = "(firstName_t:*?0* OR lastName_t:*?0* OR nickname_t:*?0* OR phone_txt:*?0* OR emergencyContactName_txt:*?0* OR emergencyContactPhone_txt:*?0* OR schoolName_t:*?0*) AND tenantId_s:?1",
fields = "id")
List<GymnastDocument> findByAll(String searchTerm, String tenantId);
}
| 870 | 0.709195 | 0.7 | 24 | 35.25 | 43.651318 | 202 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 13 |
a3a6a48f846d268bca530d46fe848f9c8b93b9c6 | 38,946,763,481,677 | fd533c9d0fd4beb88630036075b1a7b85110a7e3 | /service/src/main/java/com/github/ankurpathak/api/security/service/CustomOidcUserService.java | 012b5d794ab1f194b507c137058af27bd693e511 | []
| no_license | yassinemoumenn/spring-session-test | https://github.com/yassinemoumenn/spring-session-test | 82a58a0810d743eb789855bb11001a4723520583 | fddb263a840916bbb9a92338c12d231fbd747e43 | refs/heads/master | 2023-04-14T19:02:38.934000 | 2019-10-31T19:31:48 | 2019-10-31T19:31:48 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.github.ankurpathak.api.security.service;
import com.github.ankurpathak.api.rest.controller.dto.ApiCode;
import com.github.ankurpathak.api.security.dto.CustomUserDetails;
import org.springframework.security.oauth2.client.oidc.userinfo.OidcUserRequest;
import org.springframework.security.oauth2.client.oidc.userinfo.OidcUserService;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.oidc.user.OidcUser;
//@Component
public class CustomOidcUserService extends OidcUserService {
private final CustomOAuth2UserService oauth2UserService;
public CustomOidcUserService(CustomOAuth2UserService oauth2UserService) {
this.oauth2UserService = oauth2UserService;
}
@Override
public OidcUser loadUser(OidcUserRequest userRequest) throws OAuth2AuthenticationException {
OidcUser oidcUser = super.loadUser(userRequest);
return oauth2UserService.buildPrincipal(oidcUser, userRequest.getClientRegistration())
.map(userDetails -> CustomUserDetails.getInstance(userDetails, oidcUser))
.orElseThrow(()-> new OAuth2AuthenticationException(new OAuth2Error(String.valueOf(ApiCode.OAUTH_LOGIN_ERROR.getCode()))));
}
}
| UTF-8 | Java | 1,331 | java | CustomOidcUserService.java | Java | [
{
"context": "package com.github.ankurpathak.api.security.service;\n\n\nimport com.github.ankurpa",
"end": 30,
"score": 0.9988097548484802,
"start": 19,
"tag": "USERNAME",
"value": "ankurpathak"
},
{
"context": "rpathak.api.security.service;\n\n\nimport com.github.ankurpathak.api.rest.controller.dto.ApiCode;\nimport com.githu",
"end": 84,
"score": 0.9990424513816833,
"start": 73,
"tag": "USERNAME",
"value": "ankurpathak"
},
{
"context": "pi.rest.controller.dto.ApiCode;\nimport com.github.ankurpathak.api.security.dto.CustomUserDetails;\nimport org.sp",
"end": 147,
"score": 0.9987246990203857,
"start": 136,
"tag": "USERNAME",
"value": "ankurpathak"
}
]
| null | []
| package com.github.ankurpathak.api.security.service;
import com.github.ankurpathak.api.rest.controller.dto.ApiCode;
import com.github.ankurpathak.api.security.dto.CustomUserDetails;
import org.springframework.security.oauth2.client.oidc.userinfo.OidcUserRequest;
import org.springframework.security.oauth2.client.oidc.userinfo.OidcUserService;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.oidc.user.OidcUser;
//@Component
public class CustomOidcUserService extends OidcUserService {
private final CustomOAuth2UserService oauth2UserService;
public CustomOidcUserService(CustomOAuth2UserService oauth2UserService) {
this.oauth2UserService = oauth2UserService;
}
@Override
public OidcUser loadUser(OidcUserRequest userRequest) throws OAuth2AuthenticationException {
OidcUser oidcUser = super.loadUser(userRequest);
return oauth2UserService.buildPrincipal(oidcUser, userRequest.getClientRegistration())
.map(userDetails -> CustomUserDetails.getInstance(userDetails, oidcUser))
.orElseThrow(()-> new OAuth2AuthenticationException(new OAuth2Error(String.valueOf(ApiCode.OAUTH_LOGIN_ERROR.getCode()))));
}
}
| 1,331 | 0.801653 | 0.788881 | 29 | 44.896553 | 38.869671 | 139 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.482759 | false | false | 13 |
10397f9a90ec08356fbd5f94104d6fa437c6d537 | 14,207,751,839,355 | 43dc93a37ee2282ed736d1447ff1fe0841a1b3cb | /src/Action.java | 8ac86fac14b592fc0d6b60143fdaca2bea20d5ec | []
| no_license | clementserrano/SMANegociant | https://github.com/clementserrano/SMANegociant | 0f3b5e0f429a6f6e77b8ab20274fc3aebd594575 | 795592a6af9def14f3482d6bed63cfd088032e16 | refs/heads/master | 2020-04-16T14:26:12.832000 | 2019-02-05T16:05:20 | 2019-02-05T16:05:20 | 165,666,922 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | public enum Action {
OFFRE,
VALIDER,
ACCEPT,
REFUSE,
CONTRE_OFFRE
}
| UTF-8 | Java | 88 | java | Action.java | Java | []
| null | []
| public enum Action {
OFFRE,
VALIDER,
ACCEPT,
REFUSE,
CONTRE_OFFRE
}
| 88 | 0.579545 | 0.579545 | 7 | 11.571428 | 5.421047 | 20 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false | 13 |
8b36bb07b995a5590d5f03fb01323493819b28a5 | 33,732,673,182,306 | 28ca521064deedc7d25ca7aa571d2b6cf3b86fa6 | /f3Ftimer/src/main/java/com/marktreble/f3ftimer/data/race/RaceDatabase.java | 5f4c38763085caf14ce13433533ab8480d1a3d00 | [
"MIT"
]
| permissive | stephanherrig/f3f-timer | https://github.com/stephanherrig/f3f-timer | a3b3c2c9de59ec30f066dc170cc5e454ea72451b | faee1b2977e27f1178245a7291fd5c6ec850ed11 | refs/heads/master | 2020-05-23T02:09:56.655000 | 2019-09-19T17:32:13 | 2019-09-19T17:32:13 | 84,740,986 | 0 | 0 | null | true | 2017-03-12T16:43:05 | 2017-03-12T16:43:05 | 2016-09-26T11:35:57 | 2016-09-04T18:50:43 | 15,533 | 0 | 0 | 0 | null | null | null | package com.marktreble.f3ftimer.data.race;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class RaceDatabase extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "races.db";
private static final int DATABASE_VERSION = 10;
private static final String RACE_TABLE_CREATE = "create table races " +
"(id integer primary key," +
" name tinytext," +
" type integer," +
" offset integer," +
" status integer," +
" round integer," +
" rounds_per_flight integer," +
" start_number integer," +
" race_id integer);";
private static final String RACEPILOTS_TABLE_CREATE = "create table racepilots " +
"(id integer primary key," +
" pilot_id integer," +
" race_id integer," +
" status integer," +
" firstname tinytext," +
" lastname tinytext," +
" email tinytext," +
" frequency tinytext," +
" models tinytext," +
" nationality tinytext," +
" language tinytext, " +
" team tinytext);";
private static final String RACETIMES_TABLE_CREATE = "create table racetimes " +
"(id integer primary key," +
" pilot_id integer," +
" race_id integer," +
" round integer," +
" group_nr integer," +
" start_pos integer," +
" penalty integer," +
" time float," +
" points float," +
" reflight integer);";
private static final String RACEGROUPS_TABLE_CREATE = "create table racegroups " +
"(id integer primary key," +
" race_id integer," +
" round integer," +
" groups integer," +
" start_pilot integer);";
private static final String FASTESTLEGTIMES_TABLE_CREATE = "create table if not exists fastestLegTimes " +
"(race_id integer," +
" round integer," +
" pilot_id integer," +
" leg0 long," +
" leg1 long," +
" leg2 long," +
" leg3 long," +
" leg4 long," +
" leg5 long," +
" leg6 long," +
" leg7 long," +
" leg8 long," +
" leg9 long," +
" primary key (race_id, round, pilot_id));";
private static final String FASTESTFLIGHTTIME_TABLE_CREATE = "create table if not exists fastestFlightTime " +
"(race_id integer," +
" round integer," +
" pilot_id integer," +
" time float," +
" primary key (race_id, round, pilot_id));";
public RaceDatabase(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(RACE_TABLE_CREATE);
db.execSQL(RACEPILOTS_TABLE_CREATE);
db.execSQL(RACETIMES_TABLE_CREATE);
db.execSQL(RACEGROUPS_TABLE_CREATE);
db.execSQL(FASTESTLEGTIMES_TABLE_CREATE);
db.execSQL(FASTESTFLIGHTTIME_TABLE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(RaceDatabase.class.getName(),
"Upgrading database from version " + oldVersion + " to " + newVersion);
String sql;
if (newVersion>1 && oldVersion<=1){
sql = "alter table racepilots add nationality tinytext";
db.execSQL(sql);
sql = "alter table racepilots add language tinytext";
db.execSQL(sql);
}
if (newVersion>2 && oldVersion<=2){
db.execSQL(RACEGROUPS_TABLE_CREATE);
}
if (newVersion>3 && oldVersion<=3){
sql = "alter table races add rounds_per_flight integer";
db.execSQL(sql);
}
if (newVersion>4 && oldVersion<=4){
sql = "alter table racetimes add reflight integer";
db.execSQL(sql);
}
if (newVersion>5 && oldVersion<=5){
sql = "alter table races add start_number integer";
db.execSQL(sql);
}
if (newVersion>6 && oldVersion<=6){
sql = "alter table racepilots add team tinytext";
db.execSQL(sql);
}
if (newVersion>7 && oldVersion<=7){
sql = "alter table racegroups add start_pilot integer";
db.execSQL(sql);
}
if (newVersion>8 && oldVersion<=8){
sql = "alter table races add race_id integer";
db.execSQL(sql);
}
if (newVersion>9 && oldVersion<=9){
sql = "alter table racetimes add group_nr integer";
db.execSQL(sql);
sql = "alter table racetimes add points float";
db.execSQL(sql);
sql = "alter table racetimes add start_pos integer";
db.execSQL(sql);
}
}
}
| UTF-8 | Java | 4,563 | java | RaceDatabase.java | Java | [
{
"context": "package com.marktreble.f3ftimer.data.race;\r\n\r\nimport android.content.Con",
"end": 22,
"score": 0.7307447195053101,
"start": 16,
"tag": "USERNAME",
"value": "treble"
}
]
| null | []
| package com.marktreble.f3ftimer.data.race;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class RaceDatabase extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "races.db";
private static final int DATABASE_VERSION = 10;
private static final String RACE_TABLE_CREATE = "create table races " +
"(id integer primary key," +
" name tinytext," +
" type integer," +
" offset integer," +
" status integer," +
" round integer," +
" rounds_per_flight integer," +
" start_number integer," +
" race_id integer);";
private static final String RACEPILOTS_TABLE_CREATE = "create table racepilots " +
"(id integer primary key," +
" pilot_id integer," +
" race_id integer," +
" status integer," +
" firstname tinytext," +
" lastname tinytext," +
" email tinytext," +
" frequency tinytext," +
" models tinytext," +
" nationality tinytext," +
" language tinytext, " +
" team tinytext);";
private static final String RACETIMES_TABLE_CREATE = "create table racetimes " +
"(id integer primary key," +
" pilot_id integer," +
" race_id integer," +
" round integer," +
" group_nr integer," +
" start_pos integer," +
" penalty integer," +
" time float," +
" points float," +
" reflight integer);";
private static final String RACEGROUPS_TABLE_CREATE = "create table racegroups " +
"(id integer primary key," +
" race_id integer," +
" round integer," +
" groups integer," +
" start_pilot integer);";
private static final String FASTESTLEGTIMES_TABLE_CREATE = "create table if not exists fastestLegTimes " +
"(race_id integer," +
" round integer," +
" pilot_id integer," +
" leg0 long," +
" leg1 long," +
" leg2 long," +
" leg3 long," +
" leg4 long," +
" leg5 long," +
" leg6 long," +
" leg7 long," +
" leg8 long," +
" leg9 long," +
" primary key (race_id, round, pilot_id));";
private static final String FASTESTFLIGHTTIME_TABLE_CREATE = "create table if not exists fastestFlightTime " +
"(race_id integer," +
" round integer," +
" pilot_id integer," +
" time float," +
" primary key (race_id, round, pilot_id));";
public RaceDatabase(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(RACE_TABLE_CREATE);
db.execSQL(RACEPILOTS_TABLE_CREATE);
db.execSQL(RACETIMES_TABLE_CREATE);
db.execSQL(RACEGROUPS_TABLE_CREATE);
db.execSQL(FASTESTLEGTIMES_TABLE_CREATE);
db.execSQL(FASTESTFLIGHTTIME_TABLE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(RaceDatabase.class.getName(),
"Upgrading database from version " + oldVersion + " to " + newVersion);
String sql;
if (newVersion>1 && oldVersion<=1){
sql = "alter table racepilots add nationality tinytext";
db.execSQL(sql);
sql = "alter table racepilots add language tinytext";
db.execSQL(sql);
}
if (newVersion>2 && oldVersion<=2){
db.execSQL(RACEGROUPS_TABLE_CREATE);
}
if (newVersion>3 && oldVersion<=3){
sql = "alter table races add rounds_per_flight integer";
db.execSQL(sql);
}
if (newVersion>4 && oldVersion<=4){
sql = "alter table racetimes add reflight integer";
db.execSQL(sql);
}
if (newVersion>5 && oldVersion<=5){
sql = "alter table races add start_number integer";
db.execSQL(sql);
}
if (newVersion>6 && oldVersion<=6){
sql = "alter table racepilots add team tinytext";
db.execSQL(sql);
}
if (newVersion>7 && oldVersion<=7){
sql = "alter table racegroups add start_pilot integer";
db.execSQL(sql);
}
if (newVersion>8 && oldVersion<=8){
sql = "alter table races add race_id integer";
db.execSQL(sql);
}
if (newVersion>9 && oldVersion<=9){
sql = "alter table racetimes add group_nr integer";
db.execSQL(sql);
sql = "alter table racetimes add points float";
db.execSQL(sql);
sql = "alter table racetimes add start_pos integer";
db.execSQL(sql);
}
}
}
| 4,563 | 0.602016 | 0.595222 | 149 | 28.624161 | 21.896484 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.436242 | false | false | 13 |
df418c8a2fff0e6ea498781e9be5188c37f955bc | 10,728,828,338,208 | e21471186568c67bb4aba1c6c3e7431b67f46df4 | /jhash/src/jhash/WorkIpv6.java | 68d30393237bffb3c78f01d225fb0dda2e504c89 | []
| no_license | MVIStank/jhash | https://github.com/MVIStank/jhash | 52383a3ec8dfa749b448205ebdc037648baa4250 | e454227565f43b9df9defeb09ddc9965f48a8942 | refs/heads/master | 2022-07-09T19:43:33.601000 | 2022-05-17T05:47:01 | 2022-05-17T05:47:01 | 132,978,887 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package jhash;
import java.util.ArrayList;
import java.util.Iterator;
public class WorkIpv6 {
/*
ArrayList<String> ipv6 = new ArrayList<>();
ipv6.add("fe80");
ipv6.add("0000");
ipv6.add("0000");
ipv6.add("0000");
ipv6.add("0000");
ipv6.add("0000");
ipv6.add("0000");
ipv6.add("000c");
Gerbil dd = new Gerbil(ipv6,127);
// dd.buildSubnetIpv6();
System.out.println(dd.getSubnet());
// System.out.println(dd.getPrefix());
System.out.println(dd.getFirstAddrIpv6());
System.out.println(dd.getLastAddrIpv6());
*/
private static final int BIT_OCTET_COUNT = 16;
private ArrayList<String> ipv6Pre; // received subnet of ipv6 addr from Controller
private ArrayList<Integer> ipv6Bin; // bin of ipv6;
private ArrayList<String> ipv6String;
private int prefix; //received prefix from Controller
private String subnet; // calculated network
WorkIpv6(ArrayList<String> ipv6Pre, int prefix) {
this.ipv6Pre = ipv6Pre;
this.prefix = prefix;
start();
}
// public function returned subnet of ipv6 addr
public String getSubnet() {
ipv6String = arrayToStringBuilderPrepare(ipv6Bin);
subnet = viewOfIv6(ipv6String);
return subnet;
}
// return currently prefix
public String getPrefix (){
return "" + prefix;
}
// return first address of ipv6 subnet
public String getFirstAddrIpv6() {
ArrayList<Integer> tmp = new ArrayList<>();
StringBuilder str= new StringBuilder();
tmp = buildFirstAdrIpv6();
for (Integer integer : tmp) {
str.append(Integer.toHexString(integer));
str.append(":");
}
return str.toString();
}
//
public String getLastAddrIpv6() {
ArrayList<Integer> tmp;
tmp = buildLastAddrIpv6();
return viewOfIv6(arrayToStringBuilderPrepare(tmp));
}
//
private ArrayList<Integer> buildSubnetIpv6 () {
ArrayList<Integer> tmp;
tmp = buildBinaryIpv6();
for (int i = 0; i < tmp.size(); i++) {
if (i >= prefix) {
tmp.set(i, 0);
}
}
return tmp;
}
// initialized function
private void start(){
ipv6Bin = buildSubnetIpv6();
}
/*
Input:
Output: Integer array with ipv6 representative of dex [5200,0,200]
*/
private ArrayList<Integer> buildFirstAdrIpv6 () {
ArrayList<String> sr = arrayToStringBuilderPrepare(ipv6Bin);
// sr = [f,e,8,0]
ArrayList<Integer> tmp1 = new ArrayList<>();
StringBuilder str = new StringBuilder();
ArrayList<String> buffer = new ArrayList<>();
int count = 0;
int k = 0;
boolean tie = true;
while (tie) {
while (k < sr.size()) {
if (count == 4) {
break;
} else {
str.append(sr.get(k));
buffer.add(sr.get(k));
count++;
k++;
}
}
int m = Integer.parseInt(str.toString(), 16);
tmp1.add(m);
count = 0;
str = new StringBuilder();
if ( k == sr.size()) {
tie = false;
}
}
for (int i = tmp1.size(); i >= 0; i--) {
int h = tmp1.get((i) - 1);
if (h + 1 > 65536) {
tmp1.set(i - 1, 0);
} else {
tmp1.set(i - 1, h + 1);
break;
}
}
return tmp1;
}
////
private ArrayList<Integer> buildLastAddrIpv6 (){
ArrayList <Integer> tmp;
tmp = buildBinaryIpv6();
for (int i = 0; i < tmp.size(); i++) {
if ( i >= prefix){
tmp.set(i, 1);
}
}
return tmp;
}
/*
Preparation function
Building array of fex ipv6 addresses. Converting binary to hex
Input: array binary representative Ipv6 [1,1,1,1 ... 0,0,0,0]
Return: string array with hex of Ipv6 [ 'f', ... '0' ]
*/
private ArrayList<String> arrayToStringBuilderPrepare(ArrayList <Integer> arr){
ArrayList <String> ipv6Prepare = new ArrayList<>();
StringBuilder str = new StringBuilder();
int count = 0;
for ( int i = 0; i < arr.size()-3; i ++) {
while (count < 4) {
str.append(arr.get(i));
count ++;
i++;
}
int dec = Integer.parseInt(str.toString(), 2);
String hexString = Integer.toHexString(dec);
ipv6Prepare.add(hexString);
str = new StringBuilder();
count = 0;
i--;
}
return ipv6Prepare;
}
/*
Input: array of hex Ipv6
Return: representative of Ipv6 as String
*/
private String viewOfIv6 ( ArrayList<String> arr){
StringBuilder ipv6Representive = new StringBuilder();
ArrayList<String> buffer = new ArrayList<>();
ArrayList<String> fin = new ArrayList<>();
int count = 0;
int k = 0;
boolean tie = true;
while (tie) {
while (k < arr.size()){
if (count == 4) {
break;
}
else {
buffer.add(arr.get(k));
count++;
k++;
}
}
buffer.add(":");
Iterator<String> itr = buffer.iterator();
while (itr.hasNext()){
String rtu = itr.next();
if ( rtu.equals("0")){
itr.remove();
}
else break;
}
if (buffer.size() == 1){
buffer.add(0, "0");
}
fin.addAll(buffer);
buffer = new ArrayList<>();
count = 0;
if ( k == arr.size()) {
tie = false;
}
}
fin.remove(fin.size() - 1);
for (String s : fin) {
ipv6Representive.append(s);
}
return ipv6Representive.toString();
}
//convert hex to binary for array
// Input: String 'String'
// Return: [1,0,1,1]
private ArrayList <Integer> hexToBinaryOctet(String ipv6Oct) {
// int count = 0;
ArrayList <Integer> tmp = new ArrayList();
int t = (Integer.parseInt(ipv6Oct, 16)); // convert hex to int. For example, fe80 -> 65152
while ( t > 0 ){
int of = t % 2;
tmp.add(0,of);
t = t /2;
}
tmp = addZeroPadding(tmp);
return tmp;
}
//add zero padding
private ArrayList<Integer> addZeroPadding(ArrayList<Integer> sr) {
while (sr.size() != BIT_OCTET_COUNT) {
sr.add(0,0);
}
return sr;
}
//
private ArrayList <Integer> buildBinaryIpv6 ( ){
ArrayList <Integer> tmp;
ArrayList <Integer> tmp2 = new ArrayList ();
for (String s : ipv6Pre) {
tmp = hexToBinaryOctet(s);
tmp2.addAll(tmp);
}
return tmp2;
}
}
| UTF-8 | Java | 9,225 | java | WorkIpv6.java | Java | []
| null | []
| package jhash;
import java.util.ArrayList;
import java.util.Iterator;
public class WorkIpv6 {
/*
ArrayList<String> ipv6 = new ArrayList<>();
ipv6.add("fe80");
ipv6.add("0000");
ipv6.add("0000");
ipv6.add("0000");
ipv6.add("0000");
ipv6.add("0000");
ipv6.add("0000");
ipv6.add("000c");
Gerbil dd = new Gerbil(ipv6,127);
// dd.buildSubnetIpv6();
System.out.println(dd.getSubnet());
// System.out.println(dd.getPrefix());
System.out.println(dd.getFirstAddrIpv6());
System.out.println(dd.getLastAddrIpv6());
*/
private static final int BIT_OCTET_COUNT = 16;
private ArrayList<String> ipv6Pre; // received subnet of ipv6 addr from Controller
private ArrayList<Integer> ipv6Bin; // bin of ipv6;
private ArrayList<String> ipv6String;
private int prefix; //received prefix from Controller
private String subnet; // calculated network
WorkIpv6(ArrayList<String> ipv6Pre, int prefix) {
this.ipv6Pre = ipv6Pre;
this.prefix = prefix;
start();
}
// public function returned subnet of ipv6 addr
public String getSubnet() {
ipv6String = arrayToStringBuilderPrepare(ipv6Bin);
subnet = viewOfIv6(ipv6String);
return subnet;
}
// return currently prefix
public String getPrefix (){
return "" + prefix;
}
// return first address of ipv6 subnet
public String getFirstAddrIpv6() {
ArrayList<Integer> tmp = new ArrayList<>();
StringBuilder str= new StringBuilder();
tmp = buildFirstAdrIpv6();
for (Integer integer : tmp) {
str.append(Integer.toHexString(integer));
str.append(":");
}
return str.toString();
}
//
public String getLastAddrIpv6() {
ArrayList<Integer> tmp;
tmp = buildLastAddrIpv6();
return viewOfIv6(arrayToStringBuilderPrepare(tmp));
}
//
private ArrayList<Integer> buildSubnetIpv6 () {
ArrayList<Integer> tmp;
tmp = buildBinaryIpv6();
for (int i = 0; i < tmp.size(); i++) {
if (i >= prefix) {
tmp.set(i, 0);
}
}
return tmp;
}
// initialized function
private void start(){
ipv6Bin = buildSubnetIpv6();
}
/*
Input:
Output: Integer array with ipv6 representative of dex [5200,0,200]
*/
private ArrayList<Integer> buildFirstAdrIpv6 () {
ArrayList<String> sr = arrayToStringBuilderPrepare(ipv6Bin);
// sr = [f,e,8,0]
ArrayList<Integer> tmp1 = new ArrayList<>();
StringBuilder str = new StringBuilder();
ArrayList<String> buffer = new ArrayList<>();
int count = 0;
int k = 0;
boolean tie = true;
while (tie) {
while (k < sr.size()) {
if (count == 4) {
break;
} else {
str.append(sr.get(k));
buffer.add(sr.get(k));
count++;
k++;
}
}
int m = Integer.parseInt(str.toString(), 16);
tmp1.add(m);
count = 0;
str = new StringBuilder();
if ( k == sr.size()) {
tie = false;
}
}
for (int i = tmp1.size(); i >= 0; i--) {
int h = tmp1.get((i) - 1);
if (h + 1 > 65536) {
tmp1.set(i - 1, 0);
} else {
tmp1.set(i - 1, h + 1);
break;
}
}
return tmp1;
}
////
private ArrayList<Integer> buildLastAddrIpv6 (){
ArrayList <Integer> tmp;
tmp = buildBinaryIpv6();
for (int i = 0; i < tmp.size(); i++) {
if ( i >= prefix){
tmp.set(i, 1);
}
}
return tmp;
}
/*
Preparation function
Building array of fex ipv6 addresses. Converting binary to hex
Input: array binary representative Ipv6 [1,1,1,1 ... 0,0,0,0]
Return: string array with hex of Ipv6 [ 'f', ... '0' ]
*/
private ArrayList<String> arrayToStringBuilderPrepare(ArrayList <Integer> arr){
ArrayList <String> ipv6Prepare = new ArrayList<>();
StringBuilder str = new StringBuilder();
int count = 0;
for ( int i = 0; i < arr.size()-3; i ++) {
while (count < 4) {
str.append(arr.get(i));
count ++;
i++;
}
int dec = Integer.parseInt(str.toString(), 2);
String hexString = Integer.toHexString(dec);
ipv6Prepare.add(hexString);
str = new StringBuilder();
count = 0;
i--;
}
return ipv6Prepare;
}
/*
Input: array of hex Ipv6
Return: representative of Ipv6 as String
*/
private String viewOfIv6 ( ArrayList<String> arr){
StringBuilder ipv6Representive = new StringBuilder();
ArrayList<String> buffer = new ArrayList<>();
ArrayList<String> fin = new ArrayList<>();
int count = 0;
int k = 0;
boolean tie = true;
while (tie) {
while (k < arr.size()){
if (count == 4) {
break;
}
else {
buffer.add(arr.get(k));
count++;
k++;
}
}
buffer.add(":");
Iterator<String> itr = buffer.iterator();
while (itr.hasNext()){
String rtu = itr.next();
if ( rtu.equals("0")){
itr.remove();
}
else break;
}
if (buffer.size() == 1){
buffer.add(0, "0");
}
fin.addAll(buffer);
buffer = new ArrayList<>();
count = 0;
if ( k == arr.size()) {
tie = false;
}
}
fin.remove(fin.size() - 1);
for (String s : fin) {
ipv6Representive.append(s);
}
return ipv6Representive.toString();
}
//convert hex to binary for array
// Input: String 'String'
// Return: [1,0,1,1]
private ArrayList <Integer> hexToBinaryOctet(String ipv6Oct) {
// int count = 0;
ArrayList <Integer> tmp = new ArrayList();
int t = (Integer.parseInt(ipv6Oct, 16)); // convert hex to int. For example, fe80 -> 65152
while ( t > 0 ){
int of = t % 2;
tmp.add(0,of);
t = t /2;
}
tmp = addZeroPadding(tmp);
return tmp;
}
//add zero padding
private ArrayList<Integer> addZeroPadding(ArrayList<Integer> sr) {
while (sr.size() != BIT_OCTET_COUNT) {
sr.add(0,0);
}
return sr;
}
//
private ArrayList <Integer> buildBinaryIpv6 ( ){
ArrayList <Integer> tmp;
ArrayList <Integer> tmp2 = new ArrayList ();
for (String s : ipv6Pre) {
tmp = hexToBinaryOctet(s);
tmp2.addAll(tmp);
}
return tmp2;
}
}
| 9,225 | 0.387642 | 0.368238 | 241 | 37.273857 | 19.299337 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.659751 | false | false | 13 |
f5dba81a8c34ec0100fed81261c1d5ebe6dfe8f0 | 21,655,225,163,316 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/4/4_7da9dab0c99b831b8f5f597aa0cd0b0ac894712c/TimelineRenderer/4_7da9dab0c99b831b8f5f597aa0cd0b0ac894712c_TimelineRenderer_t.java | 2706ba7e467cd530206b0202c1ed1a1307042f8d | []
| 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 | /*
* Copyright 2011-2013 PrimeFaces Extensions.
*
* 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.
*
* $Id: $
*/
package org.primefaces.extensions.component.timeline;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import org.apache.commons.lang3.StringUtils;
import org.primefaces.extensions.model.timeline.TimelineEvent;
import org.primefaces.extensions.model.timeline.TimelineModel;
import org.primefaces.extensions.util.ComponentUtils;
import org.primefaces.extensions.util.FastStringWriter;
import org.primefaces.renderkit.CoreRenderer;
/**
* TimelineRenderer
*
* @author Oleg Varaksin / last modified by $Author: $
* @version $Revision: 1.0 $
* @since 0.7 (reimplemented)
*/
public class TimelineRenderer extends CoreRenderer {
@Override
public void decode(FacesContext context, UIComponent component) {
decodeBehaviors(context, component);
}
@Override
public void encodeEnd(FacesContext context, UIComponent component) throws IOException {
Timeline timeline = (Timeline) component;
encodeMarkup(context, timeline);
encodeScript(context, timeline);
}
protected void encodeMarkup(FacesContext context, Timeline timeline) throws IOException {
ResponseWriter writer = context.getResponseWriter();
String clientId = timeline.getClientId(context);
writer.startElement("div", timeline);
writer.writeAttribute("id", clientId, "id");
if (timeline.getStyle() != null) {
writer.writeAttribute("style", timeline.getStyle(), "style");
}
if (timeline.getStyleClass() != null) {
writer.writeAttribute("class", timeline.getStyleClass(), "styleClass");
}
writer.endElement("div");
}
protected void encodeScript(FacesContext context, Timeline timeline) throws IOException {
TimelineModel model = timeline.getValue();
if (model == null) {
return;
}
ResponseWriter writer = context.getResponseWriter();
String clientId = timeline.getClientId(context);
TimeZone timeZone = ComponentUtils.resolveTimeZone(timeline.getTimeZone());
Calendar calendar = Calendar.getInstance(timeZone);
FastStringWriter fsw = new FastStringWriter();
FastStringWriter fswHtml = new FastStringWriter();
startScript(writer, clientId);
writer.write("$(function(){");
writer.write("PrimeFacesExt.cw('Timeline','" + timeline.resolveWidgetVar() + "',{");
writer.write("id:'" + clientId + "'");
writer.write(",data:[");
// encode events
List<TimelineEvent> events = model.getEvents();
int size = events != null ? events.size() : 0;
for (int i = 0; i < size; i++) {
writer.write(encodeEvent(context, fsw, fswHtml, timeline, calendar, timeZone, events.get(i)));
if (i + 1 < size) {
writer.write(",");
}
}
writer.write("],opts:{");
// encode options
writer.write("height:'" + timeline.getHeight() + "'");
writer.write(",minHeight:" + timeline.getMinHeight());
writer.write(",width:'" + timeline.getWidth() + "'");
writer.write(",responsive:" + timeline.isResponsive());
writer.write(",axisOnTop:" + timeline.isAxisOnTop());
writer.write(",dragAreaWidth:" + timeline.getDragAreaWidth());
writer.write(",editable:" + timeline.isEditable());
writer.write(",selectable:" + timeline.isSelectable());
writer.write(",zoomable:" + timeline.isZoomable());
writer.write(",moveable:" + timeline.isMoveable());
if (timeline.getStart() != null) {
writer.write(",start:" + encodeDate(calendar, timeZone, timeline.getStart()));
}
if (timeline.getEnd() != null) {
writer.write(",end:" + encodeDate(calendar, timeZone, timeline.getEnd()));
}
if (timeline.getMin() != null) {
writer.write(",min:" + encodeDate(calendar, timeZone, timeline.getMin()));
}
if (timeline.getMax() != null) {
writer.write(",max:" + encodeDate(calendar, timeZone, timeline.getMax()));
}
writer.write(",zoomMin:" + timeline.getZoomMin());
writer.write(",zoomMax:" + timeline.getZoomMax());
writer.write(",eventMargin:" + timeline.getEventMargin());
writer.write(",eventMarginAxis:" + timeline.getEventMarginAxis());
writer.write(",style:'" + timeline.getEventStyle() + "'");
writer.write(",groupsChangeable:" + timeline.isGroupsChangeable());
writer.write(",groupsOnRight:" + timeline.isGroupsOnRight());
if (timeline.getGroupsWidth() != null) {
writer.write(",groupsWidth:'" + timeline.getGroupsWidth() + "'");
}
writer.write(",snapEvents:" + timeline.isSnapEvents());
writer.write(",stackEvents:" + timeline.isStackEvents());
writer.write(",showCurrentTime:" + timeline.isShowCurrentTime());
writer.write(",showMajorLabels:" + timeline.isShowMajorLabels());
writer.write(",showMinorLabels:" + timeline.isShowMinorLabels());
writer.write(",showButtonNew:" + timeline.isShowButtonNew());
writer.write(",showNavigation:" + timeline.isShowNavigation());
writer.write("}");
encodeClientBehaviors(context, timeline);
writer.write("},true);});");
endScript(writer);
}
public String encodeEvent(FacesContext context, FastStringWriter fsw, FastStringWriter fswHtml, Timeline timeline,
Calendar calendar, TimeZone timeZone, TimelineEvent event) throws IOException {
ResponseWriter writer = context.getResponseWriter();
fsw.write("{\"start\":" + encodeDate(calendar, timeZone, event.getStartDate()));
if (event.getEndDate() != null) {
fsw.write(",\"end\":" + encodeDate(calendar, timeZone, event.getEndDate()));
} else {
fsw.write(",\"end\":null");
}
if (event.isEditable() != null) {
fsw.write(",\"editable\":" + event.isEditable());
} else {
fsw.write(",\"editable\":null");
}
if (event.getGroup() != null) {
fsw.write(",\"group\":\"" + event.getGroup() + "\"");
} else {
fsw.write(",\"group\":null");
}
if (StringUtils.isNotBlank(event.getStyleClass())) {
fsw.write(",\"className\":\"" + event.getStyleClass() + "\"");
} else {
fsw.write(",\"className\":null");
}
fsw.write(",\"content\":\"");
if (timeline.getChildCount() > 0) {
Object data = event.getData();
if (StringUtils.isNotBlank(timeline.getVar()) && data != null) {
context.getExternalContext().getRequestMap().put(timeline.getVar(), data);
}
ResponseWriter clonedWriter = writer.cloneWithWriter(fswHtml);
context.setResponseWriter(clonedWriter);
renderChildren(context, timeline);
// restore writer
context.setResponseWriter(writer);
fsw.write(ComponentUtils.escapeHtmlTextInJson(fswHtml.toString()));
fswHtml.reset();
} else if (event.getData() != null) {
fsw.write(event.getData().toString());
}
fsw.write("\"");
fsw.write("}");
String eventJson = fsw.toString();
fsw.reset();
return eventJson;
}
// convert from UTC to locale date
private String encodeDate(Calendar calendar, TimeZone localTimeZone, Date utcDate) {
int offsetFromUTC = localTimeZone.getOffset(utcDate.getTime());
calendar.setTime(utcDate);
calendar.add(Calendar.MILLISECOND, offsetFromUTC);
return "new Date(" + calendar.getTimeInMillis() + ")";
}
@Override
public void encodeChildren(FacesContext context, UIComponent component) throws IOException {
//do nothing
}
@Override
public boolean getRendersChildren() {
return true;
}
}
| UTF-8 | Java | 8,118 | java | 4_7da9dab0c99b831b8f5f597aa0cd0b0ac894712c_TimelineRenderer_t.java | Java | [
{
"context": "erer;\n \n /**\n * TimelineRenderer\n *\n * @author Oleg Varaksin / last modified by $Author: $\n * @version $Revis",
"end": 1355,
"score": 0.9997566342353821,
"start": 1342,
"tag": "NAME",
"value": "Oleg Varaksin"
}
]
| null | []
| /*
* Copyright 2011-2013 PrimeFaces Extensions.
*
* 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.
*
* $Id: $
*/
package org.primefaces.extensions.component.timeline;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import org.apache.commons.lang3.StringUtils;
import org.primefaces.extensions.model.timeline.TimelineEvent;
import org.primefaces.extensions.model.timeline.TimelineModel;
import org.primefaces.extensions.util.ComponentUtils;
import org.primefaces.extensions.util.FastStringWriter;
import org.primefaces.renderkit.CoreRenderer;
/**
* TimelineRenderer
*
* @author <NAME> / last modified by $Author: $
* @version $Revision: 1.0 $
* @since 0.7 (reimplemented)
*/
public class TimelineRenderer extends CoreRenderer {
@Override
public void decode(FacesContext context, UIComponent component) {
decodeBehaviors(context, component);
}
@Override
public void encodeEnd(FacesContext context, UIComponent component) throws IOException {
Timeline timeline = (Timeline) component;
encodeMarkup(context, timeline);
encodeScript(context, timeline);
}
protected void encodeMarkup(FacesContext context, Timeline timeline) throws IOException {
ResponseWriter writer = context.getResponseWriter();
String clientId = timeline.getClientId(context);
writer.startElement("div", timeline);
writer.writeAttribute("id", clientId, "id");
if (timeline.getStyle() != null) {
writer.writeAttribute("style", timeline.getStyle(), "style");
}
if (timeline.getStyleClass() != null) {
writer.writeAttribute("class", timeline.getStyleClass(), "styleClass");
}
writer.endElement("div");
}
protected void encodeScript(FacesContext context, Timeline timeline) throws IOException {
TimelineModel model = timeline.getValue();
if (model == null) {
return;
}
ResponseWriter writer = context.getResponseWriter();
String clientId = timeline.getClientId(context);
TimeZone timeZone = ComponentUtils.resolveTimeZone(timeline.getTimeZone());
Calendar calendar = Calendar.getInstance(timeZone);
FastStringWriter fsw = new FastStringWriter();
FastStringWriter fswHtml = new FastStringWriter();
startScript(writer, clientId);
writer.write("$(function(){");
writer.write("PrimeFacesExt.cw('Timeline','" + timeline.resolveWidgetVar() + "',{");
writer.write("id:'" + clientId + "'");
writer.write(",data:[");
// encode events
List<TimelineEvent> events = model.getEvents();
int size = events != null ? events.size() : 0;
for (int i = 0; i < size; i++) {
writer.write(encodeEvent(context, fsw, fswHtml, timeline, calendar, timeZone, events.get(i)));
if (i + 1 < size) {
writer.write(",");
}
}
writer.write("],opts:{");
// encode options
writer.write("height:'" + timeline.getHeight() + "'");
writer.write(",minHeight:" + timeline.getMinHeight());
writer.write(",width:'" + timeline.getWidth() + "'");
writer.write(",responsive:" + timeline.isResponsive());
writer.write(",axisOnTop:" + timeline.isAxisOnTop());
writer.write(",dragAreaWidth:" + timeline.getDragAreaWidth());
writer.write(",editable:" + timeline.isEditable());
writer.write(",selectable:" + timeline.isSelectable());
writer.write(",zoomable:" + timeline.isZoomable());
writer.write(",moveable:" + timeline.isMoveable());
if (timeline.getStart() != null) {
writer.write(",start:" + encodeDate(calendar, timeZone, timeline.getStart()));
}
if (timeline.getEnd() != null) {
writer.write(",end:" + encodeDate(calendar, timeZone, timeline.getEnd()));
}
if (timeline.getMin() != null) {
writer.write(",min:" + encodeDate(calendar, timeZone, timeline.getMin()));
}
if (timeline.getMax() != null) {
writer.write(",max:" + encodeDate(calendar, timeZone, timeline.getMax()));
}
writer.write(",zoomMin:" + timeline.getZoomMin());
writer.write(",zoomMax:" + timeline.getZoomMax());
writer.write(",eventMargin:" + timeline.getEventMargin());
writer.write(",eventMarginAxis:" + timeline.getEventMarginAxis());
writer.write(",style:'" + timeline.getEventStyle() + "'");
writer.write(",groupsChangeable:" + timeline.isGroupsChangeable());
writer.write(",groupsOnRight:" + timeline.isGroupsOnRight());
if (timeline.getGroupsWidth() != null) {
writer.write(",groupsWidth:'" + timeline.getGroupsWidth() + "'");
}
writer.write(",snapEvents:" + timeline.isSnapEvents());
writer.write(",stackEvents:" + timeline.isStackEvents());
writer.write(",showCurrentTime:" + timeline.isShowCurrentTime());
writer.write(",showMajorLabels:" + timeline.isShowMajorLabels());
writer.write(",showMinorLabels:" + timeline.isShowMinorLabels());
writer.write(",showButtonNew:" + timeline.isShowButtonNew());
writer.write(",showNavigation:" + timeline.isShowNavigation());
writer.write("}");
encodeClientBehaviors(context, timeline);
writer.write("},true);});");
endScript(writer);
}
public String encodeEvent(FacesContext context, FastStringWriter fsw, FastStringWriter fswHtml, Timeline timeline,
Calendar calendar, TimeZone timeZone, TimelineEvent event) throws IOException {
ResponseWriter writer = context.getResponseWriter();
fsw.write("{\"start\":" + encodeDate(calendar, timeZone, event.getStartDate()));
if (event.getEndDate() != null) {
fsw.write(",\"end\":" + encodeDate(calendar, timeZone, event.getEndDate()));
} else {
fsw.write(",\"end\":null");
}
if (event.isEditable() != null) {
fsw.write(",\"editable\":" + event.isEditable());
} else {
fsw.write(",\"editable\":null");
}
if (event.getGroup() != null) {
fsw.write(",\"group\":\"" + event.getGroup() + "\"");
} else {
fsw.write(",\"group\":null");
}
if (StringUtils.isNotBlank(event.getStyleClass())) {
fsw.write(",\"className\":\"" + event.getStyleClass() + "\"");
} else {
fsw.write(",\"className\":null");
}
fsw.write(",\"content\":\"");
if (timeline.getChildCount() > 0) {
Object data = event.getData();
if (StringUtils.isNotBlank(timeline.getVar()) && data != null) {
context.getExternalContext().getRequestMap().put(timeline.getVar(), data);
}
ResponseWriter clonedWriter = writer.cloneWithWriter(fswHtml);
context.setResponseWriter(clonedWriter);
renderChildren(context, timeline);
// restore writer
context.setResponseWriter(writer);
fsw.write(ComponentUtils.escapeHtmlTextInJson(fswHtml.toString()));
fswHtml.reset();
} else if (event.getData() != null) {
fsw.write(event.getData().toString());
}
fsw.write("\"");
fsw.write("}");
String eventJson = fsw.toString();
fsw.reset();
return eventJson;
}
// convert from UTC to locale date
private String encodeDate(Calendar calendar, TimeZone localTimeZone, Date utcDate) {
int offsetFromUTC = localTimeZone.getOffset(utcDate.getTime());
calendar.setTime(utcDate);
calendar.add(Calendar.MILLISECOND, offsetFromUTC);
return "new Date(" + calendar.getTimeInMillis() + ")";
}
@Override
public void encodeChildren(FacesContext context, UIComponent component) throws IOException {
//do nothing
}
@Override
public boolean getRendersChildren() {
return true;
}
}
| 8,111 | 0.680217 | 0.67763 | 240 | 32.820835 | 27.926638 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.195833 | false | false | 13 |
2a2f83a6447d662d3b4313e58e34f40000179a45 | 12,618,613,954,105 | 69799c48f01c10cef4cf9abef4a8c4c4fc7c7d29 | /shaopenglai20181210/src/main/java/com/bawei/shaopenglai/presenter/IPresenterImpl.java | 6e0143e47e227fec4aaed54899ad104fa85e619b | []
| no_license | ShaoPengLai1/WeekWork | https://github.com/ShaoPengLai1/WeekWork | 421321f2eda0b834a80f10ae893e0427f8940381 | 06157f33642e8020ec665744f0be79f48e073f67 | refs/heads/master | 2020-04-10T20:29:14.336000 | 2018-12-11T03:04:14 | 2018-12-11T03:04:14 | 161,269,205 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.bawei.shaopenglai.presenter;
import com.bawei.shaopenglai.bean.SignBean;
import com.bawei.shaopenglai.model.IModelImpl;
import com.bawei.shaopenglai.callback.MyCallBack;
import com.bawei.shaopenglai.view.IView;
import java.util.Map;
public class IPresenterImpl implements IPresenter{
private IView mIview;
private IModelImpl model;
public IPresenterImpl(IView iview) {
mIview = iview;
model = new IModelImpl();
}
@Override
public void startRequest(String url, String prames, Class clazz) {
/* model.requestData(url, null, clazz, new MyCallBack() {
@Override
public void getData(Object data) {
mIview.getRequest(data);
}
});*/
}
//okhttp post请求
@Override
public void startRequestPost(String url, Map<String, String> params, Class clazz) {
model.requestDataPost(url, params, clazz, new MyCallBack() {
@Override
public void setData(Object data) {
mIview.getRequest(data);
}
});
}
public void onDetach(){
if(model!=null){
model = null;
}
if (mIview!=null){
mIview = null;
}
}
}
| UTF-8 | Java | 1,252 | java | IPresenterImpl.java | Java | []
| null | []
| package com.bawei.shaopenglai.presenter;
import com.bawei.shaopenglai.bean.SignBean;
import com.bawei.shaopenglai.model.IModelImpl;
import com.bawei.shaopenglai.callback.MyCallBack;
import com.bawei.shaopenglai.view.IView;
import java.util.Map;
public class IPresenterImpl implements IPresenter{
private IView mIview;
private IModelImpl model;
public IPresenterImpl(IView iview) {
mIview = iview;
model = new IModelImpl();
}
@Override
public void startRequest(String url, String prames, Class clazz) {
/* model.requestData(url, null, clazz, new MyCallBack() {
@Override
public void getData(Object data) {
mIview.getRequest(data);
}
});*/
}
//okhttp post请求
@Override
public void startRequestPost(String url, Map<String, String> params, Class clazz) {
model.requestDataPost(url, params, clazz, new MyCallBack() {
@Override
public void setData(Object data) {
mIview.getRequest(data);
}
});
}
public void onDetach(){
if(model!=null){
model = null;
}
if (mIview!=null){
mIview = null;
}
}
}
| 1,252 | 0.604968 | 0.604968 | 47 | 25.553192 | 20.958733 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.574468 | false | false | 13 |
8aca80ca47a4851c7e057e99cf58ff10ed54ee36 | 18,056,042,514,996 | 2263b6542c116f3e959d56ad15f2f3737eac63d4 | /src/main/java/com/dapidi/scheduler/converters/ResultSetToJobRun.java | 0e0008f25372cb61126de553ced98a9536343c0b | []
| no_license | leonj1/dapidi_scheduler | https://github.com/leonj1/dapidi_scheduler | f44f0ae14af033a99a97ff7241172ca917a55639 | 2ce767da3801707d69e4f8e8b1b0986034b300ea | refs/heads/master | 2021-01-21T11:39:33.246000 | 2017-10-25T11:05:19 | 2017-10-25T11:05:19 | 91,750,654 | 0 | 0 | null | false | 2017-05-27T21:35:07 | 2017-05-19T00:55:36 | 2017-05-19T00:55:51 | 2017-05-27T21:35:07 | 204 | 0 | 0 | 3 | Java | null | null | package com.dapidi.scheduler.converters;
import com.dapidi.scheduler.enums.JobInstanceState;
import com.dapidi.scheduler.enums.RunState;
import com.dapidi.scheduler.mappers.MyConverter;
import com.dapidi.scheduler.models.JobRun;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.UUID;
/**
* Created for K and M Consulting LLC.
* Created by Jose M Leon 2017
**/
public class ResultSetToJobRun implements MyConverter {
private String name;
private SimpleDateFormat format;
public ResultSetToJobRun() {
this.name = "JobRun";
this.format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
}
@Override
public Object object(ResultSet rs) throws SQLException, ParseException {
return new JobRun(
UUID.fromString(rs.getString("id")),
UUID.fromString(rs.getString("job_instance_id")),
RunState.valueOf(rs.getString("run_state")),
JobInstanceState.valueOf(rs.getString("job_state")),
rs.getInt("exit_code"),
this.format.parse(rs.getString("start_time")).toInstant(),
this.format.parse(rs.getString("end_time")).toInstant()
);
}
@Override
public String name() {
return this.name;
}
}
| UTF-8 | Java | 1,362 | java | ResultSetToJobRun.java | Java | [
{
"context": " Created for K and M Consulting LLC.\n * Created by Jose M Leon 2017\n **/\npublic class ResultSetToJobRun implemen",
"end": 448,
"score": 0.9998839497566223,
"start": 437,
"tag": "NAME",
"value": "Jose M Leon"
}
]
| null | []
| package com.dapidi.scheduler.converters;
import com.dapidi.scheduler.enums.JobInstanceState;
import com.dapidi.scheduler.enums.RunState;
import com.dapidi.scheduler.mappers.MyConverter;
import com.dapidi.scheduler.models.JobRun;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.UUID;
/**
* Created for K and M Consulting LLC.
* Created by <NAME> 2017
**/
public class ResultSetToJobRun implements MyConverter {
private String name;
private SimpleDateFormat format;
public ResultSetToJobRun() {
this.name = "JobRun";
this.format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
}
@Override
public Object object(ResultSet rs) throws SQLException, ParseException {
return new JobRun(
UUID.fromString(rs.getString("id")),
UUID.fromString(rs.getString("job_instance_id")),
RunState.valueOf(rs.getString("run_state")),
JobInstanceState.valueOf(rs.getString("job_state")),
rs.getInt("exit_code"),
this.format.parse(rs.getString("start_time")).toInstant(),
this.format.parse(rs.getString("end_time")).toInstant()
);
}
@Override
public String name() {
return this.name;
}
}
| 1,357 | 0.666667 | 0.66373 | 44 | 29.954546 | 23.239811 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.522727 | false | false | 13 |
6b0dbf37ed2585f7dbffc46b38527f51b2804e0d | 37,769,942,434,396 | 259d3473a47d109e5edbfdcc3b80b9087067de10 | /app/src/main/java/com/shanmukhagroup/shanmukha/DataAdapter.java | 9a5983205788e4585de7a6d6fd44477376a7aa86 | []
| no_license | mobile-android/Shanmukha | https://github.com/mobile-android/Shanmukha | be8b11d40d3f1d521ffeb9ad47940e39d2ff2dec | 2cec53efe1517125932ac32b9a88400eb9c2db3f | refs/heads/master | 2016-09-14T13:13:35.553000 | 2016-05-14T05:49:49 | 2016-05-14T05:49:49 | 58,791,184 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.shanmukhagroup.shanmukha;
import android.content.ContentValues;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
*/
public class DataAdapter {
Database database;
public DataAdapter(Context context){
database= new Database(context);
}
public long insertData(String name, String number, String email, String city, String pin)
{
SQLiteDatabase db = database.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(database.NAME, name);
contentValues.put(database.NUMBER, number);
contentValues.put(database.EMAIL, email);
contentValues.put(database.CITY, city);
contentValues.put(database.PINCODE, pin);
long id = db.insert(database.TABLE_NAME, null, contentValues);
return id;
}
/* public Cursor getData()
{
SQLiteDatabase db = database.getWritableDatabase();
String[] columns = {Database.COLUMN_UID, Database.NAME, Database.EMAIL, Database.NUMBER};
Cursor cursor = db.query(Database.TABLE_NAME, columns, null, null, null, null, null);
StringBuilder builder = new StringBuilder();
while (cursor.moveToNext())
{
int cid = cursor.getInt(0);
String name = cursor.getString(1);
String email = cursor.getString(2);
String num = cursor.getString(3);
builder.append(cid+" "+name+" "+email+" "+num+"\n");
}
return cursor;
}
public int updateData(String Name, String Email, String Numb){
SQLiteDatabase db = database.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(Database.NAME, Name);
contentValues.put(Database.EMAIL, Email);
contentValues.put(Database.NUMBER, Numb);
int count = db.update(Database.TABLE_NAME, contentValues, Database.COLUMN_UID+" =? ", null);
return count;
}*/
static class Database extends SQLiteOpenHelper{
private static final String DATABASE_NAME="cloudicadatabase";
private static final String TABLE_NAME="CLTABLE";
private static final int DATABASE_VERSION= 1;
private static final String COLUMN_UID = "_id";
private static final String NAME="Name";
private static final String NUMBER="Number";
private static final String EMAIL="Email";
private static final String CITY="City";
private static final String PINCODE="Pincode";
private static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + "(" +
COLUMN_UID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
NAME + " VARCHAR(32) NOT NULL, " +
NUMBER + " INTEGER, " +
EMAIL + " VARCHAR(25) NOT NULL, " +
CITY + " VARCHAR(50) NOT NULL, " +
PINCODE + " INTEGER);";
private static final String DROP_TABLE = "DROP TABLE "+TABLE_NAME+" IF EXISTS";
private Context context;
public Database(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(CREATE_TABLE);
} catch (SQLException e) {
Message.message(context, ""+e);
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
db.execSQL(DROP_TABLE);
onCreate(db);
} catch (SQLException e) {
Message.message(context, ""+e);
}
}
}
}
| UTF-8 | Java | 3,970 | java | DataAdapter.java | Java | []
| null | []
| package com.shanmukhagroup.shanmukha;
import android.content.ContentValues;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
*/
public class DataAdapter {
Database database;
public DataAdapter(Context context){
database= new Database(context);
}
public long insertData(String name, String number, String email, String city, String pin)
{
SQLiteDatabase db = database.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(database.NAME, name);
contentValues.put(database.NUMBER, number);
contentValues.put(database.EMAIL, email);
contentValues.put(database.CITY, city);
contentValues.put(database.PINCODE, pin);
long id = db.insert(database.TABLE_NAME, null, contentValues);
return id;
}
/* public Cursor getData()
{
SQLiteDatabase db = database.getWritableDatabase();
String[] columns = {Database.COLUMN_UID, Database.NAME, Database.EMAIL, Database.NUMBER};
Cursor cursor = db.query(Database.TABLE_NAME, columns, null, null, null, null, null);
StringBuilder builder = new StringBuilder();
while (cursor.moveToNext())
{
int cid = cursor.getInt(0);
String name = cursor.getString(1);
String email = cursor.getString(2);
String num = cursor.getString(3);
builder.append(cid+" "+name+" "+email+" "+num+"\n");
}
return cursor;
}
public int updateData(String Name, String Email, String Numb){
SQLiteDatabase db = database.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(Database.NAME, Name);
contentValues.put(Database.EMAIL, Email);
contentValues.put(Database.NUMBER, Numb);
int count = db.update(Database.TABLE_NAME, contentValues, Database.COLUMN_UID+" =? ", null);
return count;
}*/
static class Database extends SQLiteOpenHelper{
private static final String DATABASE_NAME="cloudicadatabase";
private static final String TABLE_NAME="CLTABLE";
private static final int DATABASE_VERSION= 1;
private static final String COLUMN_UID = "_id";
private static final String NAME="Name";
private static final String NUMBER="Number";
private static final String EMAIL="Email";
private static final String CITY="City";
private static final String PINCODE="Pincode";
private static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + "(" +
COLUMN_UID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
NAME + " VARCHAR(32) NOT NULL, " +
NUMBER + " INTEGER, " +
EMAIL + " VARCHAR(25) NOT NULL, " +
CITY + " VARCHAR(50) NOT NULL, " +
PINCODE + " INTEGER);";
private static final String DROP_TABLE = "DROP TABLE "+TABLE_NAME+" IF EXISTS";
private Context context;
public Database(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(CREATE_TABLE);
} catch (SQLException e) {
Message.message(context, ""+e);
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
db.execSQL(DROP_TABLE);
onCreate(db);
} catch (SQLException e) {
Message.message(context, ""+e);
}
}
}
}
| 3,970 | 0.594962 | 0.592191 | 108 | 34.759258 | 26.075344 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.87037 | false | false | 13 |
5eede19006557da8eb6e1dffebff1e75ff0fd5b8 | 39,049,842,658,245 | 70b9f3986062136b5926d0d68983b29292fd2f1a | /src/main/java/clasesDAOHibernateJPA/TareaDAOHibernateJPA.java | 8adc5b5776be7413df27807ec962277d6af8e9c4 | []
| no_license | cristian1706/Trillow | https://github.com/cristian1706/Trillow | 4bf8baad98982fb32e1d5ae68be316edb4989cfd | e09a9a253f80954bd4f5745f90863b83ea245985 | refs/heads/master | 2021-08-29T21:27:50.222000 | 2017-12-15T02:42:04 | 2017-12-15T02:42:04 | 109,896,649 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package clasesDAOHibernateJPA;
import org.springframework.stereotype.Repository;
import clasesDAO.TareaDAO;
import model.Tarea;
@Repository
public class TareaDAOHibernateJPA extends GenericDAOHibernateJPA<Tarea> implements TareaDAO{
public TareaDAOHibernateJPA() {
super(Tarea.class);
// TODO Auto-generated constructor stub
}
}
| UTF-8 | Java | 340 | java | TareaDAOHibernateJPA.java | Java | []
| null | []
| package clasesDAOHibernateJPA;
import org.springframework.stereotype.Repository;
import clasesDAO.TareaDAO;
import model.Tarea;
@Repository
public class TareaDAOHibernateJPA extends GenericDAOHibernateJPA<Tarea> implements TareaDAO{
public TareaDAOHibernateJPA() {
super(Tarea.class);
// TODO Auto-generated constructor stub
}
}
| 340 | 0.814706 | 0.814706 | 16 | 20.25 | 24.383652 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6875 | false | false | 13 |
8f3801e203e5396bbf38b601290b2e0358581bda | 22,411,139,405,867 | b7038650a191894a345a5d8704a67d8b8478b265 | /poker/src/main/java/com/slt/poker/web/UserController.java | c97d5d76a9c3ad12fb6c33b9c994d3f74f5e0621 | []
| no_license | MfkOTT/texas-poker | https://github.com/MfkOTT/texas-poker | f774f4172e8d8140babcde0f8dbdc839b05deb09 | 0fde771d998221b55f5a321da60c8b0948c3fa27 | refs/heads/master | 2021-05-20T18:01:22.199000 | 2017-03-13T02:51:39 | 2017-03-13T04:23:36 | 84,775,630 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.slt.poker.web;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSONObject;
import com.slt.base.aop.SystemControllerLog;
import com.slt.base.utils.RspUtil;
import com.slt.poker.service.PlayerService;
import com.slt.poker.service.UserService;
@Controller
@RequestMapping(value="/user")
public class UserController {
@Autowired
private UserService userService;
@Autowired
private PlayerService playerService;
@RequestMapping(value = "/login", method = RequestMethod.POST)
@ResponseBody
@SystemControllerLog(description="用户登录")
public JSONObject login(@RequestBody JSONObject paramJson) throws Exception{
final String operationCode = "001";
String param = paramJson.getString("param");
JSONObject reqJson = JSONObject.parseObject(param);
if(StringUtils.isEmpty(reqJson.getString("deviceId"))){
return RspUtil.build("fail","设备号为空");
}
JSONObject userJson = reqJson.getJSONObject("userInfo");
if(StringUtils.isEmpty(userJson.getString("loginId"))){
return RspUtil.build("fail","参数缺失");
}
if(StringUtils.isEmpty(userJson.getString("passWord"))){
return RspUtil.build("fail","参数缺失");
}
try {
return userService.login(reqJson.getString("deviceId"),userJson.getString("loginId"),userJson.getString("passWord"),operationCode);
} catch (Exception e) {
throw e;
}
}
@RequestMapping(value = "/modify", method = RequestMethod.POST)
@ResponseBody
@SystemControllerLog(description="修改密码")
public JSONObject modifyPwd(@RequestBody JSONObject paramJson) throws Exception{
final String operationCode = "002";
String param = paramJson.getString("param");
JSONObject reqJson = JSONObject.parseObject(param);
if(StringUtils.isEmpty(reqJson.getString("oldPwd"))){
return RspUtil.build("fail","参数缺失");
}
if(StringUtils.isEmpty(reqJson.getString("newPwd"))){
return RspUtil.build("fail","参数缺失");
}
JSONObject loginJson = reqJson.getJSONObject("loginInfo");
if(null == loginJson){
return RspUtil.build("fail","登录信息有误");
}
try {
JSONObject checkJson = this.userService.checkLonginInfo(loginJson.getString("userToken"),loginJson.getString("deviceId"),operationCode);
if(0 != checkJson.getIntValue("flag")){
return 1 == checkJson.getIntValue("flag") ? RspUtil.build("fail","登录信息验证失败") : RspUtil.build("timeout","凭证失效");
}
return this.userService.saveUpdatePwd(checkJson.getString("loginId"),reqJson.getString("oldPwd")
,reqJson.getString("newPwd"));
} catch (Exception e) {
throw e;
}
}
@RequestMapping(value = "/info", method = RequestMethod.POST)
@ResponseBody
@SystemControllerLog(description="初始化用户信息")
public JSONObject getUserInfo(@RequestBody JSONObject paramJson) throws Exception{
final String operationCode = "999";
String param = paramJson.getString("param");
JSONObject reqJson = JSONObject.parseObject(param);
JSONObject loginJson = reqJson.getJSONObject("loginInfo");
if(null == loginJson){
return RspUtil.build("fail","登录信息有误");
}
try {
JSONObject checkJson = this.userService.checkLonginInfo(loginJson.getString("userToken"),loginJson.getString("deviceId"),operationCode);
if(0 != checkJson.getIntValue("flag")){
return 1 == checkJson.getIntValue("flag") ? RspUtil.build("fail","登录信息验证失败") : RspUtil.build("timeout","凭证失效");
}
return this.userService.findUserInfo(checkJson.getString("loginId"),operationCode);
} catch (Exception e) {
throw e;
}
}
@RequestMapping(value = "/kpi", method = RequestMethod.POST)
@ResponseBody
@SystemControllerLog(description="数据报表")
public JSONObject getMyselfKpi(@RequestBody JSONObject reqJson) throws Exception{
final String operationCode = "004";
if(StringUtils.isEmpty(reqJson.getString("clubId"))){
return RspUtil.build("fail","参数缺失");
}
if(StringUtils.isEmpty(reqJson.getIntValue("blindType"))){
return RspUtil.build("fail","参数缺失");
}
if(StringUtils.isEmpty(reqJson.getIntValue("playerId"))){
return RspUtil.build("fail","参数缺失");
}
JSONObject loginJson = reqJson.getJSONObject("loginInfo");
if(null == loginJson){
return RspUtil.build("fail","登录信息有误");
}
try {
JSONObject checkJson = this.userService.checkLonginInfo(loginJson.getString("userToken"),loginJson.getString("deviceId"),operationCode);
if(0 != checkJson.getIntValue("flag")){
return 1 == checkJson.getIntValue("flag") ? RspUtil.build("fail","登录信息验证失败") : RspUtil.build("timeout","凭证失效");
}
return this.playerService.getMyselfKpi(checkJson.getString("loginId"),reqJson.getString("clubId"),reqJson.getIntValue("blindType"),reqJson.getString("playerId"),operationCode);
} catch (Exception e) {
throw e;
}
}
}
| UTF-8 | Java | 5,228 | java | UserController.java | Java | []
| null | []
| package com.slt.poker.web;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSONObject;
import com.slt.base.aop.SystemControllerLog;
import com.slt.base.utils.RspUtil;
import com.slt.poker.service.PlayerService;
import com.slt.poker.service.UserService;
@Controller
@RequestMapping(value="/user")
public class UserController {
@Autowired
private UserService userService;
@Autowired
private PlayerService playerService;
@RequestMapping(value = "/login", method = RequestMethod.POST)
@ResponseBody
@SystemControllerLog(description="用户登录")
public JSONObject login(@RequestBody JSONObject paramJson) throws Exception{
final String operationCode = "001";
String param = paramJson.getString("param");
JSONObject reqJson = JSONObject.parseObject(param);
if(StringUtils.isEmpty(reqJson.getString("deviceId"))){
return RspUtil.build("fail","设备号为空");
}
JSONObject userJson = reqJson.getJSONObject("userInfo");
if(StringUtils.isEmpty(userJson.getString("loginId"))){
return RspUtil.build("fail","参数缺失");
}
if(StringUtils.isEmpty(userJson.getString("passWord"))){
return RspUtil.build("fail","参数缺失");
}
try {
return userService.login(reqJson.getString("deviceId"),userJson.getString("loginId"),userJson.getString("passWord"),operationCode);
} catch (Exception e) {
throw e;
}
}
@RequestMapping(value = "/modify", method = RequestMethod.POST)
@ResponseBody
@SystemControllerLog(description="修改密码")
public JSONObject modifyPwd(@RequestBody JSONObject paramJson) throws Exception{
final String operationCode = "002";
String param = paramJson.getString("param");
JSONObject reqJson = JSONObject.parseObject(param);
if(StringUtils.isEmpty(reqJson.getString("oldPwd"))){
return RspUtil.build("fail","参数缺失");
}
if(StringUtils.isEmpty(reqJson.getString("newPwd"))){
return RspUtil.build("fail","参数缺失");
}
JSONObject loginJson = reqJson.getJSONObject("loginInfo");
if(null == loginJson){
return RspUtil.build("fail","登录信息有误");
}
try {
JSONObject checkJson = this.userService.checkLonginInfo(loginJson.getString("userToken"),loginJson.getString("deviceId"),operationCode);
if(0 != checkJson.getIntValue("flag")){
return 1 == checkJson.getIntValue("flag") ? RspUtil.build("fail","登录信息验证失败") : RspUtil.build("timeout","凭证失效");
}
return this.userService.saveUpdatePwd(checkJson.getString("loginId"),reqJson.getString("oldPwd")
,reqJson.getString("newPwd"));
} catch (Exception e) {
throw e;
}
}
@RequestMapping(value = "/info", method = RequestMethod.POST)
@ResponseBody
@SystemControllerLog(description="初始化用户信息")
public JSONObject getUserInfo(@RequestBody JSONObject paramJson) throws Exception{
final String operationCode = "999";
String param = paramJson.getString("param");
JSONObject reqJson = JSONObject.parseObject(param);
JSONObject loginJson = reqJson.getJSONObject("loginInfo");
if(null == loginJson){
return RspUtil.build("fail","登录信息有误");
}
try {
JSONObject checkJson = this.userService.checkLonginInfo(loginJson.getString("userToken"),loginJson.getString("deviceId"),operationCode);
if(0 != checkJson.getIntValue("flag")){
return 1 == checkJson.getIntValue("flag") ? RspUtil.build("fail","登录信息验证失败") : RspUtil.build("timeout","凭证失效");
}
return this.userService.findUserInfo(checkJson.getString("loginId"),operationCode);
} catch (Exception e) {
throw e;
}
}
@RequestMapping(value = "/kpi", method = RequestMethod.POST)
@ResponseBody
@SystemControllerLog(description="数据报表")
public JSONObject getMyselfKpi(@RequestBody JSONObject reqJson) throws Exception{
final String operationCode = "004";
if(StringUtils.isEmpty(reqJson.getString("clubId"))){
return RspUtil.build("fail","参数缺失");
}
if(StringUtils.isEmpty(reqJson.getIntValue("blindType"))){
return RspUtil.build("fail","参数缺失");
}
if(StringUtils.isEmpty(reqJson.getIntValue("playerId"))){
return RspUtil.build("fail","参数缺失");
}
JSONObject loginJson = reqJson.getJSONObject("loginInfo");
if(null == loginJson){
return RspUtil.build("fail","登录信息有误");
}
try {
JSONObject checkJson = this.userService.checkLonginInfo(loginJson.getString("userToken"),loginJson.getString("deviceId"),operationCode);
if(0 != checkJson.getIntValue("flag")){
return 1 == checkJson.getIntValue("flag") ? RspUtil.build("fail","登录信息验证失败") : RspUtil.build("timeout","凭证失效");
}
return this.playerService.getMyselfKpi(checkJson.getString("loginId"),reqJson.getString("clubId"),reqJson.getIntValue("blindType"),reqJson.getString("playerId"),operationCode);
} catch (Exception e) {
throw e;
}
}
}
| 5,228 | 0.745215 | 0.741627 | 125 | 39.127998 | 34.548744 | 179 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.52 | false | false | 13 |
f93683ab5987c5c0a225f8a7220ea2ba18719422 | 38,826,504,403,293 | c646d7a38ac6b3b50cf47eca3da41f18d7b3517b | /Redes/src/FileServer.java | 571fdd34211d573b6c318a5ab54e3493061ddbdb | []
| no_license | TheHaker117/Redes | https://github.com/TheHaker117/Redes | 160e08b3681dcf0823393b9f3e81de34d4fd3f79 | 3055a1e54bbdefba5f6e120e47deb851342daba3 | refs/heads/master | 2021-09-07T07:00:56.718000 | 2018-02-19T08:41:17 | 2018-02-19T08:41:17 | 122,035,290 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.file.Files;
import java.nio.file.Paths;
public class FileServer {
private ServerSocket server;
private Socket client;
private BufferedReader input;
private DataInputStream input1;
private DataOutputStream output;
private String locked = "";
public FileServer() throws Exception{
startConection();
manageConection();
// closeConection();
}
public static void main(String[] args) throws Exception{
FileServer server = new FileServer();
}
/**
* Initialize the connection. Since server (ServerSocket), client (Socket),
* input (BufferedReader), input1 (DataInputStream) and output (DataOutputStream).
* <p>
* Prints in console that the server is online and that the connection is on.
*
*
* @throws Exception
*/
private void startConection() throws Exception{
server = new ServerSocket(4444);
System.out.println("Server ONLINE");
client = server.accept();
input = new BufferedReader(new InputStreamReader(client.getInputStream()));
input1 = new DataInputStream(client.getInputStream());
output = new DataOutputStream(client.getOutputStream());
System.out.println("Conection ON: "+ client);
}
/**
* Check input for the next cases:
* - get Will return the text file.
* - lock Will lock the access to the specified file then
* will return it to modify in the client side.
* Will wait the for the command "unlock" to unlock (obviously) the file.
* - bye Will close the connection.
*
*
*
* @throws Exception
*/
private void manageConection() throws Exception{
String temp = input.readLine();
// System.out.println(temp);
// System.out.println(temp.contains("get"));
if(temp.contains("get")){
temp = temp.replace("get ", "");
if(!isLocked(temp))
getBackFile(temp);
else{
System.out.println("File locked");
closeConection();
}
}
else if(temp.contains("lock")){
locked = temp;
temp = temp.replace("lock ", "");
if(input.readLine().equals("get"))
getBackFile(temp);
else
System.out.println("Invalid action");
saveFile(input1.readInt());
if(input.readLine().equals("unlock"))
locked = "";
}
else if(temp.contains("bye"))
closeConection();
}
/**
* Save the text file in the specified path
*
*
* @param length File size
* @throws Exception See Java.io exceptions for Files interface
*/
private void saveFile(int length) throws Exception{
if(length >= 0){
byte[] bytes = new byte[length];
input1.readFully(bytes);
Files.write(Paths.get("C://Users/theha/Desktop/Text.txt"), bytes);
System.out.println("<<< File recived >>>");
}
else
System.out.println("<<< The recived data is empty >>>");
}
/**
* Sends to the client the bytes of the text file.
*
*
* @param name File path
* @throws Exception
*/
private void getBackFile(String name) throws Exception{
File file = new File(name);
byte[] bytes = Files.readAllBytes(file.toPath());
// System.out.println(Arrays.toString(bytes));
output.writeInt(bytes.length);
output.write(bytes);
System.out.println("<<< File sent >>>");
}
/**
* Checks if the specified file is locked.
*
*
* @param file File path
* @return true If the file is unlocked
* @return false If the file is locked
*/
private boolean isLocked(String file){
return file.equals(locked) ? true:false;
}
/**
*
* Close all connections in the server side.
*
*
* @throws Exception
*/
private void closeConection() throws Exception{
output.close();
input.close();
client.close();
server.close();
System.out.println("Server OFFLINE");
}
}
| UTF-8 | Java | 4,113 | java | FileServer.java | Java | []
| null | []
| import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.file.Files;
import java.nio.file.Paths;
public class FileServer {
private ServerSocket server;
private Socket client;
private BufferedReader input;
private DataInputStream input1;
private DataOutputStream output;
private String locked = "";
public FileServer() throws Exception{
startConection();
manageConection();
// closeConection();
}
public static void main(String[] args) throws Exception{
FileServer server = new FileServer();
}
/**
* Initialize the connection. Since server (ServerSocket), client (Socket),
* input (BufferedReader), input1 (DataInputStream) and output (DataOutputStream).
* <p>
* Prints in console that the server is online and that the connection is on.
*
*
* @throws Exception
*/
private void startConection() throws Exception{
server = new ServerSocket(4444);
System.out.println("Server ONLINE");
client = server.accept();
input = new BufferedReader(new InputStreamReader(client.getInputStream()));
input1 = new DataInputStream(client.getInputStream());
output = new DataOutputStream(client.getOutputStream());
System.out.println("Conection ON: "+ client);
}
/**
* Check input for the next cases:
* - get Will return the text file.
* - lock Will lock the access to the specified file then
* will return it to modify in the client side.
* Will wait the for the command "unlock" to unlock (obviously) the file.
* - bye Will close the connection.
*
*
*
* @throws Exception
*/
private void manageConection() throws Exception{
String temp = input.readLine();
// System.out.println(temp);
// System.out.println(temp.contains("get"));
if(temp.contains("get")){
temp = temp.replace("get ", "");
if(!isLocked(temp))
getBackFile(temp);
else{
System.out.println("File locked");
closeConection();
}
}
else if(temp.contains("lock")){
locked = temp;
temp = temp.replace("lock ", "");
if(input.readLine().equals("get"))
getBackFile(temp);
else
System.out.println("Invalid action");
saveFile(input1.readInt());
if(input.readLine().equals("unlock"))
locked = "";
}
else if(temp.contains("bye"))
closeConection();
}
/**
* Save the text file in the specified path
*
*
* @param length File size
* @throws Exception See Java.io exceptions for Files interface
*/
private void saveFile(int length) throws Exception{
if(length >= 0){
byte[] bytes = new byte[length];
input1.readFully(bytes);
Files.write(Paths.get("C://Users/theha/Desktop/Text.txt"), bytes);
System.out.println("<<< File recived >>>");
}
else
System.out.println("<<< The recived data is empty >>>");
}
/**
* Sends to the client the bytes of the text file.
*
*
* @param name File path
* @throws Exception
*/
private void getBackFile(String name) throws Exception{
File file = new File(name);
byte[] bytes = Files.readAllBytes(file.toPath());
// System.out.println(Arrays.toString(bytes));
output.writeInt(bytes.length);
output.write(bytes);
System.out.println("<<< File sent >>>");
}
/**
* Checks if the specified file is locked.
*
*
* @param file File path
* @return true If the file is unlocked
* @return false If the file is locked
*/
private boolean isLocked(String file){
return file.equals(locked) ? true:false;
}
/**
*
* Close all connections in the server side.
*
*
* @throws Exception
*/
private void closeConection() throws Exception{
output.close();
input.close();
client.close();
server.close();
System.out.println("Server OFFLINE");
}
}
| 4,113 | 0.630683 | 0.628252 | 176 | 21.369318 | 20.525898 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.142045 | false | false | 13 |
f2513afa6b87fa92dac942a26262deaa78495b53 | 38,826,504,403,163 | 3c973dc62d05ab2cfe026b2167a42c5c343f06fe | /keineAhnungDu-master/rpg-model/java/com/sandbox/character/RpgCharacter.java | e0474a6b76b266341dc3ee3ac6d1904b8c78923b | []
| no_license | kuroServamp/KeineAhnungDu | https://github.com/kuroServamp/KeineAhnungDu | e71a0959f40a31031fdd9c0ea5ec7087c67069e1 | 77fff61e5072c31733947d145249a14db8abeee9 | refs/heads/master | 2020-02-21T00:39:00.934000 | 2018-04-14T15:12:17 | 2018-04-14T15:12:17 | 126,470,511 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.sandbox.character;
import com.sandbox.character.description.Gender;
import com.sandbox.character.description.Job;
import com.sandbox.character.description.Race;
import com.sandbox.character.inventory.Inventory;
/**
* Grundlegende Klasse für einen Character in diesem RPG
*
* @author KuroS
*
*/
public class RpgCharacter {
private String name;
private Gender gender;
private Inventory inventory;
private Job job;
private Race race;
private Stats stat;
public Stats getStat() {
return stat;
}
public void setStat(Stats stat) {
this.stat = stat;
}
public Job getJob() {
return job;
}
public void setJob(Job job) {
this.job = job;
}
public Race getRace() {
return race;
}
public void setRace(Race race) {
this.race = race;
}
public RpgCharacter() {
this.gender = Gender.MALE;
}
public Inventory getInventory() {
return inventory;
}
public void setInventory(Inventory inventory) {
this.inventory = inventory;
}
public static String getTYPE() {
return TYPE;
}
public static void setTYPE(String tYPE) {
TYPE = tYPE;
}
public Gender getGender() {
return gender;
}
public void setGender(Gender gender) {
this.gender = gender;
}
public static String TYPE = "HUMAN";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| UTF-8 | Java | 1,449 | java | RpgCharacter.java | Java | [
{
"context": "l;r einen Character in diesem RPG\r\n * \r\n * @author KuroS\r\n *\r\n */\r\npublic class RpgCharacter {\r\n\r\n\tprivate",
"end": 321,
"score": 0.9708275198936462,
"start": 316,
"tag": "USERNAME",
"value": "KuroS"
}
]
| null | []
| package com.sandbox.character;
import com.sandbox.character.description.Gender;
import com.sandbox.character.description.Job;
import com.sandbox.character.description.Race;
import com.sandbox.character.inventory.Inventory;
/**
* Grundlegende Klasse für einen Character in diesem RPG
*
* @author KuroS
*
*/
public class RpgCharacter {
private String name;
private Gender gender;
private Inventory inventory;
private Job job;
private Race race;
private Stats stat;
public Stats getStat() {
return stat;
}
public void setStat(Stats stat) {
this.stat = stat;
}
public Job getJob() {
return job;
}
public void setJob(Job job) {
this.job = job;
}
public Race getRace() {
return race;
}
public void setRace(Race race) {
this.race = race;
}
public RpgCharacter() {
this.gender = Gender.MALE;
}
public Inventory getInventory() {
return inventory;
}
public void setInventory(Inventory inventory) {
this.inventory = inventory;
}
public static String getTYPE() {
return TYPE;
}
public static void setTYPE(String tYPE) {
TYPE = tYPE;
}
public Gender getGender() {
return gender;
}
public void setGender(Gender gender) {
this.gender = gender;
}
public static String TYPE = "HUMAN";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| 1,449 | 0.660455 | 0.660455 | 85 | 15.047059 | 15.622687 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.117647 | false | false | 13 |
47eee3c79fd68f3ae56515097b9d11d0837eabfd | 34,179,349,786,611 | ef2e21e1a97ed57e8cb9268f038db21e92356932 | /src/main/java/kr/go/gg/gpms/attachfile/service/model/AttachFileVO.java | 349063a374773509123a371c37f58d8153ab2749 | []
| no_license | ggict/gpms | https://github.com/ggict/gpms | 1881434eee9258b2bc27a4cc5fb1325daf9ae1d8 | 6e4e7d6a9435b175ca7dba32d61a80b0162d2057 | refs/heads/develop | 2022-12-15T21:19:21.900000 | 2021-01-06T06:52:22 | 2021-01-06T06:52:22 | 203,309,136 | 0 | 0 | null | false | 2022-12-06T00:33:00 | 2019-08-20T05:56:55 | 2021-01-06T06:52:30 | 2022-12-06T00:33:00 | 79,104 | 0 | 0 | 13 | JavaScript | false | false |
package kr.go.gg.gpms.attachfile.service.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import kr.go.gg.gpms.base.model.BaseVO;
/**
* 공통첨부파일
*
* @Class Name : AttachFileVO.java
* @Description : AttachFile VO class
* @Modification Information
*
* @author leehb1592@gmail.com
* @since 2017-03-29
* @version 1.0
* @see
*
* Copyright (C) All right reserved.
*/
@XmlAccessorType(javax.xml.bind.annotation.XmlAccessType.FIELD)
@XmlRootElement
@SuppressWarnings("serial")
public class AttachFileVO extends BaseVO {
public AttachFileVO() {
super();
}
/**
* TN_ATTACH_FILE.FILE_NO,
* 공통첨부파일.파일_번호
*/
@XmlElement
private String FILE_NO;
/**
* TN_ATTACH_FILE.FILE_NM,
* 공통첨부파일.파일_명
*/
@XmlElement
private java.lang.String FILE_NM;
/**
* TN_ATTACH_FILE.ORGINL_FILE_NM,
* 공통첨부파일.원본_파일_명
*/
@XmlElement
private java.lang.String ORGINL_FILE_NM;
/**
* TN_ATTACH_FILE.FILE_COURS,
* 공통첨부파일.파일_경로
*/
@XmlElement
private java.lang.String FILE_COURS;
/**
* TN_ATTACH_FILE.FILE_SIZE,
* 공통첨부파일.파일_크기
*/
@XmlElement
private String FILE_SIZE;
/**
* TN_ATTACH_FILE.USE_AT,
* 공통첨부파일.사용_여부
*/
@XmlElement
private java.lang.String USE_AT;
/**
* TN_ATTACH_FILE.DELETE_AT,
* 공통첨부파일.삭제_여부
*/
@XmlElement
private java.lang.String DELETE_AT;
/**
* TN_ATTACH_FILE.CRTR_NO,
* 공통첨부파일.생성자_번호
*/
@XmlElement
private String CRTR_NO;
/**
* TN_ATTACH_FILE.CREAT_DT,
* 공통첨부파일.생성_일시
*/
@XmlElement
private java.sql.Date CREAT_DT;
/**
* TN_ATTACH_FILE.UPDUSR_NO,
* 공통첨부파일.수정자_번호
*/
@XmlElement
private String UPDUSR_NO;
/**
* TN_ATTACH_FILE.UPDT_DT,
* 공통첨부파일.수정_일시
*/
@XmlElement
private java.sql.Date UPDT_DT;
//파일번호
@XmlElement
private String FILE_NUM;
@XmlElement
private String FILE_DETAIL_NO;
@XmlElement
private String FILE_SE_CODE;
@XmlElement
private String ROOT_FILE_COURS;
@XmlElement
private String SRVY_YEAR;
/**
* TN_ATTACH_FILE.FILE_NO,
* 공통첨부파일.파일_번호 값읽기
* @return
*/
@JsonProperty(value="FILE_NO")
public String getFILE_NO() {
return this.FILE_NO;
}
/**
* TN_ATTACH_FILE.FILE_NO,
* 공통첨부파일.파일_번호 값설정
* @param fileNo
*/
public void setFILE_NO(String fileNo) {
this.FILE_NO = fileNo;
}
/**
* TN_ATTACH_FILE.FILE_NM,
* 공통첨부파일.파일_명 값읽기
* @return
*/
@JsonProperty(value="FILE_NM")
public java.lang.String getFILE_NM() {
return this.FILE_NM;
}
/**
* TN_ATTACH_FILE.FILE_NM,
* 공통첨부파일.파일_명 값설정
* @param fileNm
*/
public void setFILE_NM(java.lang.String fileNm) {
this.FILE_NM = fileNm;
}
/**
* TN_ATTACH_FILE.ORGINL_FILE_NM,
* 공통첨부파일.원본_파일_명 값읽기
* @return
*/
@JsonProperty(value="ORGINL_FILE_NM")
public java.lang.String getORGINL_FILE_NM() {
return this.ORGINL_FILE_NM;
}
/**
* TN_ATTACH_FILE.ORGINL_FILE_NM,
* 공통첨부파일.원본_파일_명 값설정
* @param orginlFileNm
*/
public void setORGINL_FILE_NM(java.lang.String orginlFileNm) {
this.ORGINL_FILE_NM = orginlFileNm;
}
/**
* TN_ATTACH_FILE.FILE_COURS,
* 공통첨부파일.파일_경로 값읽기
* @return
*/
@JsonProperty(value="FILE_COURS")
public java.lang.String getFILE_COURS() {
return this.FILE_COURS;
}
/**
* TN_ATTACH_FILE.FILE_COURS,
* 공통첨부파일.파일_경로 값설정
* @param fileCours
*/
public void setFILE_COURS(java.lang.String fileCours) {
this.FILE_COURS = fileCours;
}
/**
* TN_ATTACH_FILE.FILE_SIZE,
* 공통첨부파일.파일_크기 값읽기
* @return
*/
@JsonProperty(value="FILE_SIZE")
public String getFILE_SIZE() {
return this.FILE_SIZE;
}
/**
* TN_ATTACH_FILE.FILE_SIZE,
* 공통첨부파일.파일_크기 값설정
* @param fileMg
*/
public void setFILE_SIZE(String fileMg) {
this.FILE_SIZE = fileMg;
}
/**
* TN_ATTACH_FILE.USE_AT,
* 공통첨부파일.사용_여부 값읽기
* @return
*/
@JsonProperty(value="USE_AT")
public java.lang.String getUSE_AT() {
return this.USE_AT;
}
/**
* TN_ATTACH_FILE.USE_AT,
* 공통첨부파일.사용_여부 값설정
* @param useAt
*/
public void setUSE_AT(java.lang.String useAt) {
this.USE_AT = useAt;
}
/**
* TN_ATTACH_FILE.DELETE_AT,
* 공통첨부파일.삭제_여부 값읽기
* @return
*/
@JsonProperty(value="DELETE_AT")
public java.lang.String getDELETE_AT() {
return this.DELETE_AT;
}
/**
* TN_ATTACH_FILE.DELETE_AT,
* 공통첨부파일.삭제_여부 값설정
* @param deleteAt
*/
public void setDELETE_AT(java.lang.String deleteAt) {
this.DELETE_AT = deleteAt;
}
/**
* TN_ATTACH_FILE.CRTR_NO,
* 공통첨부파일.생성자_번호 값읽기
* @return
*/
@JsonProperty(value="CRTR_NO")
public String getCRTR_NO() {
return this.CRTR_NO;
}
/**
* TN_ATTACH_FILE.CRTR_NO,
* 공통첨부파일.생성자_번호 값설정
* @param crtrNo
*/
public void setCRTR_NO(String crtrNo) {
this.CRTR_NO = crtrNo;
}
/**
* TN_ATTACH_FILE.CREAT_DT,
* 공통첨부파일.생성_일시 값읽기
* @return
*/
@JsonProperty(value="CREAT_DT")
public java.sql.Date getCREAT_DT() {
return this.CREAT_DT;
}
/**
* TN_ATTACH_FILE.CREAT_DT,
* 공통첨부파일.생성_일시 값설정
* @param creatDt
*/
public void setCREAT_DT(java.sql.Date creatDt) {
this.CREAT_DT = creatDt;
}
/**
* TN_ATTACH_FILE.UPDUSR_NO,
* 공통첨부파일.수정자_번호 값읽기
* @return
*/
@JsonProperty(value="UPDUSR_NO")
public String getUPDUSR_NO() {
return this.UPDUSR_NO;
}
/**
* TN_ATTACH_FILE.UPDUSR_NO,
* 공통첨부파일.수정자_번호 값설정
* @param updusrNo
*/
public void setUPDUSR_NO(String updusrNo) {
this.UPDUSR_NO = updusrNo;
}
/**
* TN_ATTACH_FILE.UPDT_DT,
* 공통첨부파일.수정_일시 값읽기
* @return
*/
@JsonProperty(value="UPDT_DT")
public java.sql.Date getUPDT_DT() {
return this.UPDT_DT;
}
/**
* TN_ATTACH_FILE.UPDT_DT,
* 공통첨부파일.수정_일시 값설정
* @param updtDt
*/
public void setUPDT_DT(java.sql.Date updtDt) {
this.UPDT_DT = updtDt;
}
@JsonProperty(value="FILE_NUM")
public String getFILE_NUM() {
return this.FILE_NUM;
}
public void setFILE_NUM(String fILE_NUM) {
this.FILE_NUM = fILE_NUM;
}
@JsonProperty(value="FILE_DETAIL_NO")
public String getFILE_DETAIL_NO() {
return FILE_DETAIL_NO;
}
public void setFILE_DETAIL_NO(String fILE_DETAIL_NO) {
FILE_DETAIL_NO = fILE_DETAIL_NO;
}
@JsonProperty(value="FILE_SE_CODE")
public String getFILE_SE_CODE() {
return FILE_SE_CODE;
}
public void setFILE_SE_CODE(String fILE_SE_CODE) {
FILE_SE_CODE = fILE_SE_CODE;
}
public String getROOT_FILE_COURS() {
return ROOT_FILE_COURS;
}
public void setROOT_FILE_COURS(String rOOT_FILE_COURS) {
ROOT_FILE_COURS = rOOT_FILE_COURS;
}
public String getSRVY_YEAR() {
return SRVY_YEAR;
}
public void setSRVY_YEAR(String sRVY_YEAR) {
SRVY_YEAR = sRVY_YEAR;
}
}
| UTF-8 | Java | 7,436 | java | AttachFileVO.java | Java | [
{
"context": "O class\n * @Modification Information\n *\n * @author leehb1592@gmail.com\n * @since 2017-03-29\n * @version 1.0\n * @see\n *\n ",
"end": 442,
"score": 0.9999029040336609,
"start": 423,
"tag": "EMAIL",
"value": "leehb1592@gmail.com"
}
]
| null | []
|
package kr.go.gg.gpms.attachfile.service.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import kr.go.gg.gpms.base.model.BaseVO;
/**
* 공통첨부파일
*
* @Class Name : AttachFileVO.java
* @Description : AttachFile VO class
* @Modification Information
*
* @author <EMAIL>
* @since 2017-03-29
* @version 1.0
* @see
*
* Copyright (C) All right reserved.
*/
@XmlAccessorType(javax.xml.bind.annotation.XmlAccessType.FIELD)
@XmlRootElement
@SuppressWarnings("serial")
public class AttachFileVO extends BaseVO {
public AttachFileVO() {
super();
}
/**
* TN_ATTACH_FILE.FILE_NO,
* 공통첨부파일.파일_번호
*/
@XmlElement
private String FILE_NO;
/**
* TN_ATTACH_FILE.FILE_NM,
* 공통첨부파일.파일_명
*/
@XmlElement
private java.lang.String FILE_NM;
/**
* TN_ATTACH_FILE.ORGINL_FILE_NM,
* 공통첨부파일.원본_파일_명
*/
@XmlElement
private java.lang.String ORGINL_FILE_NM;
/**
* TN_ATTACH_FILE.FILE_COURS,
* 공통첨부파일.파일_경로
*/
@XmlElement
private java.lang.String FILE_COURS;
/**
* TN_ATTACH_FILE.FILE_SIZE,
* 공통첨부파일.파일_크기
*/
@XmlElement
private String FILE_SIZE;
/**
* TN_ATTACH_FILE.USE_AT,
* 공통첨부파일.사용_여부
*/
@XmlElement
private java.lang.String USE_AT;
/**
* TN_ATTACH_FILE.DELETE_AT,
* 공통첨부파일.삭제_여부
*/
@XmlElement
private java.lang.String DELETE_AT;
/**
* TN_ATTACH_FILE.CRTR_NO,
* 공통첨부파일.생성자_번호
*/
@XmlElement
private String CRTR_NO;
/**
* TN_ATTACH_FILE.CREAT_DT,
* 공통첨부파일.생성_일시
*/
@XmlElement
private java.sql.Date CREAT_DT;
/**
* TN_ATTACH_FILE.UPDUSR_NO,
* 공통첨부파일.수정자_번호
*/
@XmlElement
private String UPDUSR_NO;
/**
* TN_ATTACH_FILE.UPDT_DT,
* 공통첨부파일.수정_일시
*/
@XmlElement
private java.sql.Date UPDT_DT;
//파일번호
@XmlElement
private String FILE_NUM;
@XmlElement
private String FILE_DETAIL_NO;
@XmlElement
private String FILE_SE_CODE;
@XmlElement
private String ROOT_FILE_COURS;
@XmlElement
private String SRVY_YEAR;
/**
* TN_ATTACH_FILE.FILE_NO,
* 공통첨부파일.파일_번호 값읽기
* @return
*/
@JsonProperty(value="FILE_NO")
public String getFILE_NO() {
return this.FILE_NO;
}
/**
* TN_ATTACH_FILE.FILE_NO,
* 공통첨부파일.파일_번호 값설정
* @param fileNo
*/
public void setFILE_NO(String fileNo) {
this.FILE_NO = fileNo;
}
/**
* TN_ATTACH_FILE.FILE_NM,
* 공통첨부파일.파일_명 값읽기
* @return
*/
@JsonProperty(value="FILE_NM")
public java.lang.String getFILE_NM() {
return this.FILE_NM;
}
/**
* TN_ATTACH_FILE.FILE_NM,
* 공통첨부파일.파일_명 값설정
* @param fileNm
*/
public void setFILE_NM(java.lang.String fileNm) {
this.FILE_NM = fileNm;
}
/**
* TN_ATTACH_FILE.ORGINL_FILE_NM,
* 공통첨부파일.원본_파일_명 값읽기
* @return
*/
@JsonProperty(value="ORGINL_FILE_NM")
public java.lang.String getORGINL_FILE_NM() {
return this.ORGINL_FILE_NM;
}
/**
* TN_ATTACH_FILE.ORGINL_FILE_NM,
* 공통첨부파일.원본_파일_명 값설정
* @param orginlFileNm
*/
public void setORGINL_FILE_NM(java.lang.String orginlFileNm) {
this.ORGINL_FILE_NM = orginlFileNm;
}
/**
* TN_ATTACH_FILE.FILE_COURS,
* 공통첨부파일.파일_경로 값읽기
* @return
*/
@JsonProperty(value="FILE_COURS")
public java.lang.String getFILE_COURS() {
return this.FILE_COURS;
}
/**
* TN_ATTACH_FILE.FILE_COURS,
* 공통첨부파일.파일_경로 값설정
* @param fileCours
*/
public void setFILE_COURS(java.lang.String fileCours) {
this.FILE_COURS = fileCours;
}
/**
* TN_ATTACH_FILE.FILE_SIZE,
* 공통첨부파일.파일_크기 값읽기
* @return
*/
@JsonProperty(value="FILE_SIZE")
public String getFILE_SIZE() {
return this.FILE_SIZE;
}
/**
* TN_ATTACH_FILE.FILE_SIZE,
* 공통첨부파일.파일_크기 값설정
* @param fileMg
*/
public void setFILE_SIZE(String fileMg) {
this.FILE_SIZE = fileMg;
}
/**
* TN_ATTACH_FILE.USE_AT,
* 공통첨부파일.사용_여부 값읽기
* @return
*/
@JsonProperty(value="USE_AT")
public java.lang.String getUSE_AT() {
return this.USE_AT;
}
/**
* TN_ATTACH_FILE.USE_AT,
* 공통첨부파일.사용_여부 값설정
* @param useAt
*/
public void setUSE_AT(java.lang.String useAt) {
this.USE_AT = useAt;
}
/**
* TN_ATTACH_FILE.DELETE_AT,
* 공통첨부파일.삭제_여부 값읽기
* @return
*/
@JsonProperty(value="DELETE_AT")
public java.lang.String getDELETE_AT() {
return this.DELETE_AT;
}
/**
* TN_ATTACH_FILE.DELETE_AT,
* 공통첨부파일.삭제_여부 값설정
* @param deleteAt
*/
public void setDELETE_AT(java.lang.String deleteAt) {
this.DELETE_AT = deleteAt;
}
/**
* TN_ATTACH_FILE.CRTR_NO,
* 공통첨부파일.생성자_번호 값읽기
* @return
*/
@JsonProperty(value="CRTR_NO")
public String getCRTR_NO() {
return this.CRTR_NO;
}
/**
* TN_ATTACH_FILE.CRTR_NO,
* 공통첨부파일.생성자_번호 값설정
* @param crtrNo
*/
public void setCRTR_NO(String crtrNo) {
this.CRTR_NO = crtrNo;
}
/**
* TN_ATTACH_FILE.CREAT_DT,
* 공통첨부파일.생성_일시 값읽기
* @return
*/
@JsonProperty(value="CREAT_DT")
public java.sql.Date getCREAT_DT() {
return this.CREAT_DT;
}
/**
* TN_ATTACH_FILE.CREAT_DT,
* 공통첨부파일.생성_일시 값설정
* @param creatDt
*/
public void setCREAT_DT(java.sql.Date creatDt) {
this.CREAT_DT = creatDt;
}
/**
* TN_ATTACH_FILE.UPDUSR_NO,
* 공통첨부파일.수정자_번호 값읽기
* @return
*/
@JsonProperty(value="UPDUSR_NO")
public String getUPDUSR_NO() {
return this.UPDUSR_NO;
}
/**
* TN_ATTACH_FILE.UPDUSR_NO,
* 공통첨부파일.수정자_번호 값설정
* @param updusrNo
*/
public void setUPDUSR_NO(String updusrNo) {
this.UPDUSR_NO = updusrNo;
}
/**
* TN_ATTACH_FILE.UPDT_DT,
* 공통첨부파일.수정_일시 값읽기
* @return
*/
@JsonProperty(value="UPDT_DT")
public java.sql.Date getUPDT_DT() {
return this.UPDT_DT;
}
/**
* TN_ATTACH_FILE.UPDT_DT,
* 공통첨부파일.수정_일시 값설정
* @param updtDt
*/
public void setUPDT_DT(java.sql.Date updtDt) {
this.UPDT_DT = updtDt;
}
@JsonProperty(value="FILE_NUM")
public String getFILE_NUM() {
return this.FILE_NUM;
}
public void setFILE_NUM(String fILE_NUM) {
this.FILE_NUM = fILE_NUM;
}
@JsonProperty(value="FILE_DETAIL_NO")
public String getFILE_DETAIL_NO() {
return FILE_DETAIL_NO;
}
public void setFILE_DETAIL_NO(String fILE_DETAIL_NO) {
FILE_DETAIL_NO = fILE_DETAIL_NO;
}
@JsonProperty(value="FILE_SE_CODE")
public String getFILE_SE_CODE() {
return FILE_SE_CODE;
}
public void setFILE_SE_CODE(String fILE_SE_CODE) {
FILE_SE_CODE = fILE_SE_CODE;
}
public String getROOT_FILE_COURS() {
return ROOT_FILE_COURS;
}
public void setROOT_FILE_COURS(String rOOT_FILE_COURS) {
ROOT_FILE_COURS = rOOT_FILE_COURS;
}
public String getSRVY_YEAR() {
return SRVY_YEAR;
}
public void setSRVY_YEAR(String sRVY_YEAR) {
SRVY_YEAR = sRVY_YEAR;
}
}
| 7,424 | 0.65124 | 0.649123 | 378 | 16.489418 | 14.832794 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.113757 | false | false | 13 |
8321a3bfcb199d14df7de33df97e16631e487e2f | 30,897,994,781,475 | 79f1fa570fb984675f90a7e20fc4fe4e03d1c5ca | /baselibrary/src/main/java/com/endless/study/baselibrary/common/download/DownloadObserver.java | 55dd8b05ebaae1ac1653dadbfd60b1a391757d61 | []
| no_license | hsy1992/Android-Component-MVVM | https://github.com/hsy1992/Android-Component-MVVM | d2af1191b11ce0dd0dfc7a208e82af6eadba580d | 52fc6417d5a88b150efecc7010a67bf2945c44b8 | refs/heads/master | 2020-04-18T07:43:19.126000 | 2019-06-27T00:24:19 | 2019-06-27T00:24:19 | 167,370,097 | 3 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.endless.study.baselibrary.common.download;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
/**
* 下载观察者
* @author haosiyuan
* @date 2019/4/5 2:00 PM
*/
public class DownloadObserver implements Observer {
@Override
public void onSubscribe(Disposable disposable) {
}
@Override
public void onNext(Object object) {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
}
| UTF-8 | Java | 542 | java | DownloadObserver.java | Java | [
{
"context": "sposables.Disposable;\r\n\r\n/**\r\n * 下载观察者\r\n * @author haosiyuan\r\n * @date 2019/4/5 2:00 PM\r\n */\r\npublic class Dow",
"end": 171,
"score": 0.9996384382247925,
"start": 162,
"tag": "USERNAME",
"value": "haosiyuan"
}
]
| null | []
| package com.endless.study.baselibrary.common.download;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
/**
* 下载观察者
* @author haosiyuan
* @date 2019/4/5 2:00 PM
*/
public class DownloadObserver implements Observer {
@Override
public void onSubscribe(Disposable disposable) {
}
@Override
public void onNext(Object object) {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
}
| 542 | 0.635338 | 0.618421 | 32 | 14.625 | 17.513834 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.09375 | false | false | 13 |
03a9cfcf13f67a072113274f05fe84084285961b | 37,864,431,696,208 | 89ddbd9628c312cb790b28695dce36e61a4ae8e5 | /fileManager/src/sql/SqlConnect.java | d53d0c6ddcacc2f65c961f76202edf6c0f85785b | []
| no_license | ixufeng/fileManager | https://github.com/ixufeng/fileManager | 544576387735bbaadd079d1cdc54c8e5d9e2af62 | 2e122e7e69c5efcdba7db0bbb577c8884e35f805 | refs/heads/master | 2021-01-10T10:27:39.199000 | 2016-04-07T09:40:49 | 2016-04-07T09:40:49 | 54,682,379 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package sql;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Connection;
import file.PathConfig;
public class SqlConnect {
private static Connection conn = null;
public static Connection getConnection(){
String urlString = PathConfig.SQLURL;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(urlString);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
return conn;
}
public static void closeConnection(){
try {
if (conn != null || !conn.isClosed())
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| UTF-8 | Java | 785 | java | SqlConnect.java | Java | []
| null | []
| package sql;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Connection;
import file.PathConfig;
public class SqlConnect {
private static Connection conn = null;
public static Connection getConnection(){
String urlString = PathConfig.SQLURL;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(urlString);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
return conn;
}
public static void closeConnection(){
try {
if (conn != null || !conn.isClosed())
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| 785 | 0.677707 | 0.677707 | 45 | 16.444445 | 15.824813 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.888889 | false | false | 13 |
94a4a0409a6f05bbcccbd5e6ddd12d56276c9277 | 37,864,431,698,890 | 252727d3edbcea6a2de7b8b2af69cc562ce9522c | /GoogleMapTest/app/src/main/java/com/hvngoc/googlemaptest/activity/Global.java | 9a30237c06747d5384ca0e34654d1fc6b41fa32f | []
| no_license | hvngoc/thesis | https://github.com/hvngoc/thesis | b4bf74ac9645311f5dc6c9853c67f3e0c48b5f79 | 24c9855f4e747078f75cebf46f246043bc95cda0 | refs/heads/master | 2021-01-21T04:47:46.850000 | 2016-07-18T14:36:28 | 2016-07-18T14:36:28 | 50,222,468 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.hvngoc.googlemaptest.activity;
import android.content.Context;
import com.hvngoc.googlemaptest.R;
import com.hvngoc.googlemaptest.helper.StartedUserHelper;
import com.hvngoc.googlemaptest.model.Profile;
import com.hvngoc.googlemaptest.model.User;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
/**
* Created by 12125_000 on 1/9/2016.
*/
public class GLOBAL {
public static Context CurrentContext = null;
public static User CurrentUser = null;
public static int MAIN_PAGE_POSITION_VIEW = CONSTANT.BOTTOM_HOME;
public static StartedUserHelper startedUserHelper = null;
public static String TOUR_ON_STARTING = null;
//public static final String SERVER_URL = "http://10.0.3.2:9000/api/";
//public static final String SERVER_IMAGE_URL = "http://10.0.3.2:9000/images/";
public static final String SERVER_URL = "http://e8876cc5.ngrok.io/api/";
public static final String SERVER_IMAGE_URL = "http://e8876cc5.ngrok.io/images/";
public static HashMap<String, String> NOTIFICATION = null;
public static HashMap<String, ArrayList<Object>> EMOTION = null;
public static boolean needFragmentRefresh = false;
public static void initNOTIFICATION(){
NOTIFICATION = new HashMap<String, String>(){
{
put(CONSTANT.NOTIFICATION_CONFIRM_FRIEND, CurrentContext.getString(R.string.notification_string_confirm_friend));
put(CONSTANT.NOTIFICATION_FRIEND_POST, CurrentContext.getString(R.string.notification_string_friend_post));
put(CONSTANT.NOTIFICATION_MY_POST, CurrentContext.getString(R.string.notification_string_my_post));
put(CONSTANT.NOTIFICATION_COMMENT, CurrentContext.getString(R.string.notification_string_comment));
put(CONSTANT.NOTIFICATION_LIKE, CurrentContext.getString(R.string.notification_string_like));
put(CONSTANT.NOTIFICATION_SHARE, CurrentContext.getString(R.string.notification_string_share));
put(CONSTANT.NOTIFICATION_COMMENT_TOUR, CurrentContext.getString(R.string.notification_string_comment));
put(CONSTANT.NOTIFICATION_LIKE_TOUR, CurrentContext.getString(R.string.notification_string_like));
put(CONSTANT.NOTIFICATION_SHARE_TOUR, CurrentContext.getString(R.string.notification_string_share));
}
};
EMOTION = new HashMap<String, ArrayList<Object>>(){
{
put(CONSTANT.EMOTION_STRING_FUNNY, new ArrayList<Object>(Arrays.asList(GLOBAL.CurrentContext.getString(R.string.feeling_funny) ,R.drawable.markers_emotion_funny)));
put(CONSTANT.EMOTION_STRING_HAPPY, new ArrayList<Object>(Arrays.asList(GLOBAL.CurrentContext.getString(R.string.feeling_happy), R.drawable.markers_emotion_happy)));
put(CONSTANT.EMOTION_STRING_MONEY, new ArrayList<Object>(Arrays.asList(GLOBAL.CurrentContext.getString(R.string.feeling_money), R.drawable.markers_emotion_money)));
put(CONSTANT.EMOTION_STRING_NORMAL, new ArrayList<Object>(Arrays.asList(GLOBAL.CurrentContext.getString(R.string.feeling_normal), R.drawable.markers_emotion_normal)));
put(CONSTANT.EMOTION_STRING_REFUSE, new ArrayList<Object>(Arrays.asList(GLOBAL.CurrentContext.getString(R.string.feeling_refuse), R.drawable.markers_emotion_refuse)));
put(CONSTANT.EMOTION_STRING_SAD, new ArrayList<Object>(Arrays.asList(GLOBAL.CurrentContext.getString(R.string.feeling_sad), R.drawable.markers_emotion_sad)));
put(CONSTANT.EMOTION_STRING_SCARED, new ArrayList<Object>(Arrays.asList(GLOBAL.CurrentContext.getString(R.string.feeling_scare), R.drawable.markers_emotion_scared)));
put(CONSTANT.EMOTION_STRING_SLEEPY, new ArrayList<Object>(Arrays.asList(GLOBAL.CurrentContext.getString(R.string.feeling_sleepy), R.drawable.markers_emotion_sleepy)));
put(CONSTANT.EMOTION_STRING_SURPRISE, new ArrayList<Object>(Arrays.asList(GLOBAL.CurrentContext.getString(R.string.feeling_surprise), R.drawable.markers_emotion_surprise)));
put(CONSTANT.EMOTION_STRING_TERRIBLE, new ArrayList<Object>(Arrays.asList(GLOBAL.CurrentContext.getString(R.string.feeling_terrible), R.drawable.markers_emotion_terrible)));
}
};
}
}
| UTF-8 | Java | 4,339 | java | Global.java | Java | [
{
"context": "ays;\nimport java.util.HashMap;\n\n/**\n * Created by 12125_000 on 1/9/2016.\n */\npublic class GLOBAL {\n\n ",
"end": 361,
"score": 0.6076481938362122,
"start": 360,
"tag": "USERNAME",
"value": "1"
},
{
"context": "ys;\nimport java.util.HashMap;\n\n/**\n * Created by 12125_000 on 1/9/2016.\n */\npublic class GLOBAL {\n\n ",
"end": 362,
"score": 0.5052170157432556,
"start": 361,
"tag": "PASSWORD",
"value": "2"
},
{
"context": "s;\nimport java.util.HashMap;\n\n/**\n * Created by 12125_000 on 1/9/2016.\n */\npublic class GLOBAL {\n\n publi",
"end": 369,
"score": 0.5442106127738953,
"start": 362,
"tag": "USERNAME",
"value": "125_000"
},
{
"context": "//public static final String SERVER_URL = \"http://10.0.3.2:9000/api/\";\n //public static final String SERV",
"end": 751,
"score": 0.9996756315231323,
"start": 743,
"tag": "IP_ADDRESS",
"value": "10.0.3.2"
},
{
"context": "ic static final String SERVER_IMAGE_URL = \"http://10.0.3.2:9000/images/\";\n public static final String SER",
"end": 832,
"score": 0.9996770620346069,
"start": 824,
"tag": "IP_ADDRESS",
"value": "10.0.3.2"
}
]
| null | []
| package com.hvngoc.googlemaptest.activity;
import android.content.Context;
import com.hvngoc.googlemaptest.R;
import com.hvngoc.googlemaptest.helper.StartedUserHelper;
import com.hvngoc.googlemaptest.model.Profile;
import com.hvngoc.googlemaptest.model.User;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
/**
* Created by 12125_000 on 1/9/2016.
*/
public class GLOBAL {
public static Context CurrentContext = null;
public static User CurrentUser = null;
public static int MAIN_PAGE_POSITION_VIEW = CONSTANT.BOTTOM_HOME;
public static StartedUserHelper startedUserHelper = null;
public static String TOUR_ON_STARTING = null;
//public static final String SERVER_URL = "http://10.0.3.2:9000/api/";
//public static final String SERVER_IMAGE_URL = "http://10.0.3.2:9000/images/";
public static final String SERVER_URL = "http://e8876cc5.ngrok.io/api/";
public static final String SERVER_IMAGE_URL = "http://e8876cc5.ngrok.io/images/";
public static HashMap<String, String> NOTIFICATION = null;
public static HashMap<String, ArrayList<Object>> EMOTION = null;
public static boolean needFragmentRefresh = false;
public static void initNOTIFICATION(){
NOTIFICATION = new HashMap<String, String>(){
{
put(CONSTANT.NOTIFICATION_CONFIRM_FRIEND, CurrentContext.getString(R.string.notification_string_confirm_friend));
put(CONSTANT.NOTIFICATION_FRIEND_POST, CurrentContext.getString(R.string.notification_string_friend_post));
put(CONSTANT.NOTIFICATION_MY_POST, CurrentContext.getString(R.string.notification_string_my_post));
put(CONSTANT.NOTIFICATION_COMMENT, CurrentContext.getString(R.string.notification_string_comment));
put(CONSTANT.NOTIFICATION_LIKE, CurrentContext.getString(R.string.notification_string_like));
put(CONSTANT.NOTIFICATION_SHARE, CurrentContext.getString(R.string.notification_string_share));
put(CONSTANT.NOTIFICATION_COMMENT_TOUR, CurrentContext.getString(R.string.notification_string_comment));
put(CONSTANT.NOTIFICATION_LIKE_TOUR, CurrentContext.getString(R.string.notification_string_like));
put(CONSTANT.NOTIFICATION_SHARE_TOUR, CurrentContext.getString(R.string.notification_string_share));
}
};
EMOTION = new HashMap<String, ArrayList<Object>>(){
{
put(CONSTANT.EMOTION_STRING_FUNNY, new ArrayList<Object>(Arrays.asList(GLOBAL.CurrentContext.getString(R.string.feeling_funny) ,R.drawable.markers_emotion_funny)));
put(CONSTANT.EMOTION_STRING_HAPPY, new ArrayList<Object>(Arrays.asList(GLOBAL.CurrentContext.getString(R.string.feeling_happy), R.drawable.markers_emotion_happy)));
put(CONSTANT.EMOTION_STRING_MONEY, new ArrayList<Object>(Arrays.asList(GLOBAL.CurrentContext.getString(R.string.feeling_money), R.drawable.markers_emotion_money)));
put(CONSTANT.EMOTION_STRING_NORMAL, new ArrayList<Object>(Arrays.asList(GLOBAL.CurrentContext.getString(R.string.feeling_normal), R.drawable.markers_emotion_normal)));
put(CONSTANT.EMOTION_STRING_REFUSE, new ArrayList<Object>(Arrays.asList(GLOBAL.CurrentContext.getString(R.string.feeling_refuse), R.drawable.markers_emotion_refuse)));
put(CONSTANT.EMOTION_STRING_SAD, new ArrayList<Object>(Arrays.asList(GLOBAL.CurrentContext.getString(R.string.feeling_sad), R.drawable.markers_emotion_sad)));
put(CONSTANT.EMOTION_STRING_SCARED, new ArrayList<Object>(Arrays.asList(GLOBAL.CurrentContext.getString(R.string.feeling_scare), R.drawable.markers_emotion_scared)));
put(CONSTANT.EMOTION_STRING_SLEEPY, new ArrayList<Object>(Arrays.asList(GLOBAL.CurrentContext.getString(R.string.feeling_sleepy), R.drawable.markers_emotion_sleepy)));
put(CONSTANT.EMOTION_STRING_SURPRISE, new ArrayList<Object>(Arrays.asList(GLOBAL.CurrentContext.getString(R.string.feeling_surprise), R.drawable.markers_emotion_surprise)));
put(CONSTANT.EMOTION_STRING_TERRIBLE, new ArrayList<Object>(Arrays.asList(GLOBAL.CurrentContext.getString(R.string.feeling_terrible), R.drawable.markers_emotion_terrible)));
}
};
}
}
| 4,339 | 0.724821 | 0.715142 | 69 | 61.884056 | 62.202927 | 189 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.086957 | false | false | 13 |
407ab157e59eb2aa51e9dc37e9e3d36ad540fff8 | 4,758,823,832,477 | 971db87e18bf9c4ba8ee347e41573a9145cb1d6c | /src/com/doublesunflower/core/ui/search/WebSearchActivity.java | 13580c65db782d4a2eb492d487a067cd02e4af94 | []
| no_license | andrewzeus/twask2 | https://github.com/andrewzeus/twask2 | df753a6a5f41d32fb042a346acfa2bb41f7fdb0e | a7250e67f0d91b69698296235047c819086c1620 | refs/heads/master | 2021-01-18T14:02:42.371000 | 2010-04-03T04:12:27 | 2010-04-03T04:12:27 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.doublesunflower.core.ui.search;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TableRow;
import android.widget.TextView;
import com.doublesunflower.R;
import com.doublesunflower.core.ui.util.Util;
public class WebSearchActivity extends Activity {
private static final String TAG = "WebSearchActivity";
private static String GOOGLE_URL = "http://www.google.com";
private static WebView webview;
protected ImageButton btnBack;
protected ImageButton btnNew;
protected ImageButton btnSearch;
protected ImageButton btnSynchronize;
protected String query = "qualcomm";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.web);
webview = (WebView)findViewById(R.id.webview);
doSearch();
}
protected void doSearch(){
try{
webview.loadUrl(GOOGLE_URL + "/search?q=" + query);
}catch (Exception ex){
Util.showErrorDialog(this, ex);
}
}
protected void initializeUI(){
TableRow trToolbar = (TableRow) findViewById(R.id.trToolbar);
//trToolbar.setBackgroundDrawable(getWallpaper());
TableRow trTitle = (TableRow) findViewById(R.id.trTitle);
//trTitle.setBackgroundDrawable(getWallpaper());
btnBack = (ImageButton)findViewById(R.id.btnBack);
btnBack.setOnClickListener(new OnClickListener(){
// @Override
public void onClick(View arg) {
onClickBtnBack();
}
});
btnSearch = (ImageButton)findViewById(R.id.btnSearch);
btnSearch.setOnClickListener(new OnClickListener(){
// @Override
public void onClick(View arg) {
onClickBtnSearch();
}
});
TextView txtTitle = (TextView) findViewById(R.id.txtTitle);
txtTitle.setText(getResources().getString(R.string.menu_maps_item_web));
ImageView iconTitle = (ImageView) findViewById(R.id.iconTitle);
iconTitle.setImageDrawable(getResources().getDrawable(R.drawable.world));
}
protected void onClickBtnBack(){
finish();
}
protected void onClickBtnSearch(){
doSearch();
}
@Override
public void onNewIntent(final Intent newIntent)
{
super.onNewIntent(newIntent);
if (Intent.ACTION_SEARCH.equals(newIntent.getAction()))
{
query = newIntent.getStringExtra(SearchManager.QUERY);
doSearch();
}
}
}
| UTF-8 | Java | 2,852 | java | WebSearchActivity.java | Java | []
| null | []
| package com.doublesunflower.core.ui.search;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TableRow;
import android.widget.TextView;
import com.doublesunflower.R;
import com.doublesunflower.core.ui.util.Util;
public class WebSearchActivity extends Activity {
private static final String TAG = "WebSearchActivity";
private static String GOOGLE_URL = "http://www.google.com";
private static WebView webview;
protected ImageButton btnBack;
protected ImageButton btnNew;
protected ImageButton btnSearch;
protected ImageButton btnSynchronize;
protected String query = "qualcomm";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.web);
webview = (WebView)findViewById(R.id.webview);
doSearch();
}
protected void doSearch(){
try{
webview.loadUrl(GOOGLE_URL + "/search?q=" + query);
}catch (Exception ex){
Util.showErrorDialog(this, ex);
}
}
protected void initializeUI(){
TableRow trToolbar = (TableRow) findViewById(R.id.trToolbar);
//trToolbar.setBackgroundDrawable(getWallpaper());
TableRow trTitle = (TableRow) findViewById(R.id.trTitle);
//trTitle.setBackgroundDrawable(getWallpaper());
btnBack = (ImageButton)findViewById(R.id.btnBack);
btnBack.setOnClickListener(new OnClickListener(){
// @Override
public void onClick(View arg) {
onClickBtnBack();
}
});
btnSearch = (ImageButton)findViewById(R.id.btnSearch);
btnSearch.setOnClickListener(new OnClickListener(){
// @Override
public void onClick(View arg) {
onClickBtnSearch();
}
});
TextView txtTitle = (TextView) findViewById(R.id.txtTitle);
txtTitle.setText(getResources().getString(R.string.menu_maps_item_web));
ImageView iconTitle = (ImageView) findViewById(R.id.iconTitle);
iconTitle.setImageDrawable(getResources().getDrawable(R.drawable.world));
}
protected void onClickBtnBack(){
finish();
}
protected void onClickBtnSearch(){
doSearch();
}
@Override
public void onNewIntent(final Intent newIntent)
{
super.onNewIntent(newIntent);
if (Intent.ACTION_SEARCH.equals(newIntent.getAction()))
{
query = newIntent.getStringExtra(SearchManager.QUERY);
doSearch();
}
}
}
| 2,852 | 0.667602 | 0.667602 | 103 | 25.68932 | 21.063026 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.320388 | false | false | 13 |
7d8d7b72a93e233263dcb6f26d574122960aa63c | 5,763,846,113,541 | 0763eca361a4bf96f5847807b781a989e1736ee4 | /src/main/java/bill/lau/datagrid/controller/BookController.java | d3090b804dba9249967bd03824f0fb20f3a06e14 | []
| no_license | JavaProgrammerLB/bill-datagrid | https://github.com/JavaProgrammerLB/bill-datagrid | 104b7e39af7971fa445bbff9546fd66cd3700a86 | 5456060d228c89b516c7b45dd119bc10dc66ecdc | refs/heads/main | 2023-02-19T00:21:42.881000 | 2021-01-09T09:18:55 | 2021-01-09T09:18:55 | 322,545,850 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package bill.lau.datagrid.controller;
import bill.lau.datagrid.dao.BookMapper;
import bill.lau.datagrid.entity.BaseResponse;
import bill.lau.datagrid.entity.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
public class BookController {
@Autowired
public BookMapper bookMapper;
@GetMapping("/book/{id}")
public BaseResponse<Book> getBooksById(@PathVariable Integer id) {
Book book = bookMapper.findById(id);
BaseResponse response = new BaseResponse();
response.setSuccess(true);
response.setMsg("Success");
response.setData(book);
return response;
}
@PostMapping("/book")
public BaseResponse<String> insertBook(@RequestBody Book book) {
bookMapper.insert(book);
BaseResponse response = new BaseResponse();
response.setSuccess(true);
response.setMsg("Success");
response.setData("Insert Success");
return response;
}
@DeleteMapping("/book/{id}")
public BaseResponse<String> delete(@PathVariable Integer id) {
bookMapper.delete(id);
BaseResponse response = new BaseResponse();
response.setData("Delete Success");
response.setMsg("Successs");
response.setSuccess(true);
return response;
}
@PutMapping("/book")
public BaseResponse<String> update(@RequestBody Book book) {
if (book.getId() == null) {
BaseResponse response = new BaseResponse();
response.setData("ID shouldn't be null");
response.setMsg("Parameter ERROR");
response.setSuccess(false);
return response;
}
bookMapper.update(book);
BaseResponse response = new BaseResponse();
response.setData("Update Success");
response.setMsg("Successs");
response.setSuccess(true);
return response;
}
@PostMapping("/searchBook")
public BaseResponse<List<Book>> findByParam(@RequestBody Book book) {
List<Book> books = bookMapper.findByParam(book);
BaseResponse response = new BaseResponse();
response.setData(books);
response.setMsg("Success");
response.setSuccess(true);
return response;
}
@GetMapping("/books")
public BaseResponse<List<Book>> getAllBooks() {
List<Book> books = bookMapper.getAllBooks();
BaseResponse response = new BaseResponse();
response.setData(books);
response.setMsg("Success");
response.setSuccess(true);
return response;
}
}
| UTF-8 | Java | 2,658 | java | BookController.java | Java | []
| null | []
| package bill.lau.datagrid.controller;
import bill.lau.datagrid.dao.BookMapper;
import bill.lau.datagrid.entity.BaseResponse;
import bill.lau.datagrid.entity.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
public class BookController {
@Autowired
public BookMapper bookMapper;
@GetMapping("/book/{id}")
public BaseResponse<Book> getBooksById(@PathVariable Integer id) {
Book book = bookMapper.findById(id);
BaseResponse response = new BaseResponse();
response.setSuccess(true);
response.setMsg("Success");
response.setData(book);
return response;
}
@PostMapping("/book")
public BaseResponse<String> insertBook(@RequestBody Book book) {
bookMapper.insert(book);
BaseResponse response = new BaseResponse();
response.setSuccess(true);
response.setMsg("Success");
response.setData("Insert Success");
return response;
}
@DeleteMapping("/book/{id}")
public BaseResponse<String> delete(@PathVariable Integer id) {
bookMapper.delete(id);
BaseResponse response = new BaseResponse();
response.setData("Delete Success");
response.setMsg("Successs");
response.setSuccess(true);
return response;
}
@PutMapping("/book")
public BaseResponse<String> update(@RequestBody Book book) {
if (book.getId() == null) {
BaseResponse response = new BaseResponse();
response.setData("ID shouldn't be null");
response.setMsg("Parameter ERROR");
response.setSuccess(false);
return response;
}
bookMapper.update(book);
BaseResponse response = new BaseResponse();
response.setData("Update Success");
response.setMsg("Successs");
response.setSuccess(true);
return response;
}
@PostMapping("/searchBook")
public BaseResponse<List<Book>> findByParam(@RequestBody Book book) {
List<Book> books = bookMapper.findByParam(book);
BaseResponse response = new BaseResponse();
response.setData(books);
response.setMsg("Success");
response.setSuccess(true);
return response;
}
@GetMapping("/books")
public BaseResponse<List<Book>> getAllBooks() {
List<Book> books = bookMapper.getAllBooks();
BaseResponse response = new BaseResponse();
response.setData(books);
response.setMsg("Success");
response.setSuccess(true);
return response;
}
}
| 2,658 | 0.64936 | 0.64936 | 84 | 30.642857 | 19.426689 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.583333 | false | false | 13 |
66a7157091c05e804daa0129d7cbd9ae3a7b4665 | 4,612,794,939,306 | 23a9dee2dcc869ecb7eb7fed81174a59cbd2dedc | /src/main/java/com/todolist/todolist/repositories/ItemGroupRepository.java | 205cb90b392cbc378e3258c920ca514c4fa80314 | []
| no_license | SantinelX/ToDoList | https://github.com/SantinelX/ToDoList | 0869cd758ce7e1dbd2f105dc904027068f036bd3 | 92257ce77ec55638c121d2cbebfd6c062238fd25 | refs/heads/master | 2023-04-08T04:34:08.720000 | 2021-04-17T10:35:31 | 2021-04-17T10:35:31 | 351,327,255 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.todolist.todolist.repositories;
import com.todolist.todolist.model.ItemGroup;
import org.springframework.data.jpa.repository.JpaRepository;
public interface ItemGroupRepository extends JpaRepository <ItemGroup, Long> {
}
| UTF-8 | Java | 236 | java | ItemGroupRepository.java | Java | []
| null | []
| package com.todolist.todolist.repositories;
import com.todolist.todolist.model.ItemGroup;
import org.springframework.data.jpa.repository.JpaRepository;
public interface ItemGroupRepository extends JpaRepository <ItemGroup, Long> {
}
| 236 | 0.838983 | 0.838983 | 8 | 28.5 | 29.962477 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 13 |
0eb3a72ebdbe10a1cc634d91ca65d49e7ec1ec89 | 4,612,794,937,662 | 698fd2e7a2b7ab75c8bdf81146e5e65871ffce27 | /src/main/java/de/heiden/c64dt/net/drive/NetDrive.java | df8522aa5a4a28eec1f08f8bb156ba05080e304e | []
| no_license | mgrossmann/c64dt | https://github.com/mgrossmann/c64dt | bb6af640b7342d5f461d5c7b6c127e510928ddd0 | aba63fe28d23e38ebd5b5313f4271135f3e7fe79 | refs/heads/master | 2017-09-02T11:42:27.074000 | 2014-10-30T23:02:25 | 2014-10-30T23:02:25 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package de.heiden.c64dt.net.drive;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;
import java.io.File;
import java.io.IOException;
import java.net.SocketException;
/**
* Net drive server.
* Contains glue logic to connect drive connection with a device.
*/
public class NetDrive {
/**
* Logger.
*/
private final Logger logger = LoggerFactory.getLogger(getClass());
private volatile boolean isRunning;
private Thread thread;
private DriveConnection connection;
private Device device;
/**
* Constructor.
*
* @param root root directory
*/
public NetDrive(File root) throws IOException {
this(root, DriveConnection.DEFAULT_PORT);
}
/**
* Constructor.
*
* @param root root directory
* @param port server port
*/
public NetDrive(File root, int port) throws IOException {
Assert.notNull(root, "Precondition: root != null");
Assert.isTrue(root.isDirectory(), "Precondition: root.isDirectory()");
isRunning = false;
thread = null;
connection = new DriveConnection(port);
device = new Device(root);
}
/**
* Is the server running?
*/
public boolean isRunning() {
return isRunning;
}
/**
* Start server.
*/
public void start() throws IOException {
Assert.isTrue(!isRunning(), "Precondition: !isRunning()");
isRunning = true;
thread = new Thread(new Server(), "Net drive server on " + connection.getSource());
thread.start();
}
/**
* Stop server.
*/
public void stop() {
Assert.isTrue(isRunning(), "Precondition: isRunning()");
isRunning = false;
thread.interrupt();
try {
connection.close();
} catch (IOException e) {
logger.error("Failed to close drive connection");
return;
}
try {
thread.join();
} catch (InterruptedException e) {
// ignore
}
}
private class Server implements Runnable {
@Override
public void run() {
while (isRunning) {
logger.info("Net drive server up and running");
try {
connection.open();
while (isRunning) {
try {
DrivePacket received = connection.waitForRequest();
logger.debug("Received packet from " + connection.getDestination());
switch (received.getService()) {
case DriveConnection.SERVICE_OPEN: {
logger.info("OPEN " + received.getLogicalFile() + "," + received.getDevice() + "," + received.getChannel());
try {
device.open(received.getChannel(), strip0(received.getData()));
connection.sendReply(Error.OK);
} catch (DeviceException e) {
connection.sendReply(e.getError());
}
break;
}
case DriveConnection.SERVICE_CHKIN: {
logger.info("CHKIN " + received.getLogicalFile() + "," + received.getDevice() + "," + received.getChannel());
try {
device.incrementPosition(received.getChannel(), received.getData0());
connection.sendReply(Error.OK);
} catch (DeviceException e) {
connection.sendReply(e.getError());
}
break;
}
case DriveConnection.SERVICE_READ: {
logger.info("READ " + received.getLogicalFile() + "," + received.getDevice() + "," + received.getChannel());
try {
byte[] data = device.read(received.getChannel(), received.getData0());
connection.sendReply(data);
} catch (DeviceException e) {
// TODO correct?
connection.sendReply(e.getError());
}
break;
}
case DriveConnection.SERVICE_WRITE: {
logger.info("WRITE " + received.getLogicalFile() + "," + received.getDevice() + "," + received.getChannel());
try {
device.write(received.getChannel(), received.getData());
connection.sendReply(Error.OK);
} catch (DeviceException e) {
connection.sendReply(e.getError());
}
break;
}
case DriveConnection.SERVICE_CLOSE: {
logger.info("CLOSE " + received.getLogicalFile() + "," + received.getDevice() + "," + received.getChannel());
try {
device.close(received.getChannel());
connection.sendReply(Error.OK);
} catch (DeviceException e) {
connection.sendReply(e.getError());
}
break;
}
default: {
logger.error("Unknown service " + Integer.toHexString(received.getService()));
}
}
} catch (IOException e) {
logger.error("Server error", e);
}
}
} catch (SocketException e) {
logger.info("Aborted waiting for connections");
return;
} catch (IOException e) {
logger.error("Failed to connect to server port", e);
return;
}
}
logger.info("Net drive server has been shut down");
}
}
private byte[] strip0(byte[] data) {
if (data[data.length - 1] != 0x00) {
return data;
}
byte[] result = new byte[data.length - 1];
System.arraycopy(data, 0, result, 0, result.length);
return result;
}
}
| UTF-8 | Java | 5,735 | java | NetDrive.java | Java | []
| null | []
| package de.heiden.c64dt.net.drive;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;
import java.io.File;
import java.io.IOException;
import java.net.SocketException;
/**
* Net drive server.
* Contains glue logic to connect drive connection with a device.
*/
public class NetDrive {
/**
* Logger.
*/
private final Logger logger = LoggerFactory.getLogger(getClass());
private volatile boolean isRunning;
private Thread thread;
private DriveConnection connection;
private Device device;
/**
* Constructor.
*
* @param root root directory
*/
public NetDrive(File root) throws IOException {
this(root, DriveConnection.DEFAULT_PORT);
}
/**
* Constructor.
*
* @param root root directory
* @param port server port
*/
public NetDrive(File root, int port) throws IOException {
Assert.notNull(root, "Precondition: root != null");
Assert.isTrue(root.isDirectory(), "Precondition: root.isDirectory()");
isRunning = false;
thread = null;
connection = new DriveConnection(port);
device = new Device(root);
}
/**
* Is the server running?
*/
public boolean isRunning() {
return isRunning;
}
/**
* Start server.
*/
public void start() throws IOException {
Assert.isTrue(!isRunning(), "Precondition: !isRunning()");
isRunning = true;
thread = new Thread(new Server(), "Net drive server on " + connection.getSource());
thread.start();
}
/**
* Stop server.
*/
public void stop() {
Assert.isTrue(isRunning(), "Precondition: isRunning()");
isRunning = false;
thread.interrupt();
try {
connection.close();
} catch (IOException e) {
logger.error("Failed to close drive connection");
return;
}
try {
thread.join();
} catch (InterruptedException e) {
// ignore
}
}
private class Server implements Runnable {
@Override
public void run() {
while (isRunning) {
logger.info("Net drive server up and running");
try {
connection.open();
while (isRunning) {
try {
DrivePacket received = connection.waitForRequest();
logger.debug("Received packet from " + connection.getDestination());
switch (received.getService()) {
case DriveConnection.SERVICE_OPEN: {
logger.info("OPEN " + received.getLogicalFile() + "," + received.getDevice() + "," + received.getChannel());
try {
device.open(received.getChannel(), strip0(received.getData()));
connection.sendReply(Error.OK);
} catch (DeviceException e) {
connection.sendReply(e.getError());
}
break;
}
case DriveConnection.SERVICE_CHKIN: {
logger.info("CHKIN " + received.getLogicalFile() + "," + received.getDevice() + "," + received.getChannel());
try {
device.incrementPosition(received.getChannel(), received.getData0());
connection.sendReply(Error.OK);
} catch (DeviceException e) {
connection.sendReply(e.getError());
}
break;
}
case DriveConnection.SERVICE_READ: {
logger.info("READ " + received.getLogicalFile() + "," + received.getDevice() + "," + received.getChannel());
try {
byte[] data = device.read(received.getChannel(), received.getData0());
connection.sendReply(data);
} catch (DeviceException e) {
// TODO correct?
connection.sendReply(e.getError());
}
break;
}
case DriveConnection.SERVICE_WRITE: {
logger.info("WRITE " + received.getLogicalFile() + "," + received.getDevice() + "," + received.getChannel());
try {
device.write(received.getChannel(), received.getData());
connection.sendReply(Error.OK);
} catch (DeviceException e) {
connection.sendReply(e.getError());
}
break;
}
case DriveConnection.SERVICE_CLOSE: {
logger.info("CLOSE " + received.getLogicalFile() + "," + received.getDevice() + "," + received.getChannel());
try {
device.close(received.getChannel());
connection.sendReply(Error.OK);
} catch (DeviceException e) {
connection.sendReply(e.getError());
}
break;
}
default: {
logger.error("Unknown service " + Integer.toHexString(received.getService()));
}
}
} catch (IOException e) {
logger.error("Server error", e);
}
}
} catch (SocketException e) {
logger.info("Aborted waiting for connections");
return;
} catch (IOException e) {
logger.error("Failed to connect to server port", e);
return;
}
}
logger.info("Net drive server has been shut down");
}
}
private byte[] strip0(byte[] data) {
if (data[data.length - 1] != 0x00) {
return data;
}
byte[] result = new byte[data.length - 1];
System.arraycopy(data, 0, result, 0, result.length);
return result;
}
}
| 5,735 | 0.535309 | 0.532694 | 184 | 30.168478 | 27.370424 | 127 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.532609 | false | false | 13 |
fb1481fcc1dd34a3d94469f1759ed0ff2fff0ce9 | 23,046,794,576,052 | e85693860f1ff450a36a2c0594e340c77f067dba | /src/main/java/nl/tudelft/ewi/f1manager/view/savelist/NamePrompt.java | b91f655ee0331cabe1473b3641b0f0e6f7e0ea4b | [
"MIT"
]
| permissive | gerarts/f1manager | https://github.com/gerarts/f1manager | 24ed26295dbcd35a4294c2fbddfb126fecc3908c | 1642805e6a23398e0ca8450f4bd2e987643fcd69 | refs/heads/master | 2018-04-14T10:37:19.426000 | 2017-05-04T22:45:03 | 2017-05-04T22:45:03 | 74,018,913 | 0 | 0 | null | false | 2017-05-04T22:38:32 | 2016-11-17T11:05:05 | 2017-05-04T22:31:19 | 2017-05-04T22:38:32 | 37,799 | 2 | 0 | 0 | Java | null | null | package nl.tudelft.ewi.f1manager.view.savelist;
import javafx.scene.Group;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import nl.tudelft.ewi.f1manager.controller.GameController;
import nl.tudelft.ewi.f1manager.view.F1Screen;
import nl.tudelft.ewi.f1manager.view.RenderThread;
import nl.tudelft.ewi.f1manager.view.menuscreens.MenuScreen;
/**
* Created by Stijn on 30/01/2017.
*/
public class NamePrompt extends Group {
private MenuScreen menuScreen;
private SaveGroup saveGroup;
private TextField textField;
/**
* A popup containing a textfield to insert the name of the save.
*
* @param menuScreen The screen the popup is on
* @param saveGroup The place to put the new save
*/
public NamePrompt(MenuScreen menuScreen, SaveGroup saveGroup) {
this.menuScreen = menuScreen;
this.saveGroup = saveGroup;
this.setLayoutX(0);
this.setLayoutY(0);
double screenHeight = F1Screen.getScreenHt();
double screenWidth = F1Screen.getScreenWd() - F1Screen.getMenuWd();
double promptHeight = screenHeight / 4;
double promptWidth = screenWidth / 4;
Text label = new Text("Team name:");
label.setWrappingWidth((promptWidth / 10) * 8);
textField = new TextField();
Rectangle background = new Rectangle();
double backgroundX = F1Screen.getMenuWd() + screenWidth / 2 - promptWidth / 2;
double backgroundY = screenHeight / 2 - promptHeight / 2;
background.setHeight(promptHeight);
background.setWidth(promptWidth);
background.setX(backgroundX);
background.setY(backgroundY);
background.setArcHeight(10);
background.setArcWidth(10);
background.setOpacity(0.7);
textField.setPrefWidth((promptWidth / 10) * 8);
textField.setLayoutX(backgroundX + promptWidth / 10);
textField.setLayoutY(screenHeight / 2 - promptHeight / 2 + promptHeight / 3);
textField.setPrefHeight(promptHeight / 3);
label.setLayoutX(backgroundX + promptWidth / 10);
label.setLayoutY(screenHeight / 2 - promptHeight / 2 + promptHeight / 3);
label.setFont(Font.font("Verdana", FontWeight.BOLD, 40));
Button confirm = new Button();
confirm.setText("Confirm");
confirm.setLayoutY(screenHeight / 2 - promptHeight / 2
+ (promptHeight / 3) * 2 + promptHeight / 12);
confirm.setLayoutX(backgroundX + promptWidth - promptWidth / 3 - promptWidth / 10);
confirm.setPrefHeight(promptHeight / 6);
confirm.setPrefWidth(promptWidth / 3);
confirm.setOnMouseClicked(new ConfirmMouseHandler(this));
confirm.setOnKeyPressed(new ConfirmKeyHandler(this));
Button cancel = new Button();
cancel.setText("Cancel");
cancel.setLayoutY(screenHeight / 2 - promptHeight / 2
+ (promptHeight / 3) * 2 + promptHeight / 12);
cancel.setLayoutX(backgroundX + promptWidth / 10);
cancel.setPrefHeight(promptHeight / 6);
cancel.setPrefWidth(promptWidth / 3);
cancel.setOnKeyPressed(new CancelKeyHandler(this));
cancel.setOnMouseClicked(new CancelMouseHandler(this));
this.getChildren().add(background);
this.getChildren().add(label);
this.getChildren().add(textField);
this.getChildren().add(confirm);
this.getChildren().add(cancel);
double labelY = screenHeight / 2 - promptHeight / 2
+ promptHeight / 3 - ((promptHeight / 3)
- label.getLayoutBounds().getHeight()) / 2;
double labelX = backgroundX + promptWidth / 10 + (promptWidth
- label.getLayoutBounds().getWidth()) / 4;
label.setLayoutY(labelY);
label.setLayoutX(labelX);
menuScreen.getChildren().add(this);
textField.requestFocus();
}
/**
* Confirms the name you put into the field.
*/
public void confirm() {
if (textField.getText() == null || textField.getText().equals("")) {
textField.setText("Nameless");
}
GameController.getGamecontrol().initTeam(textField.getText(), 200000000);
RenderThread.renderThread.switchToScreen("NewGameScreen");
remove();
}
public void remove() {
menuScreen.getChildren().remove(this);
}
}
| UTF-8 | Java | 4,535 | java | NamePrompt.java | Java | [
{
"context": "er.view.menuscreens.MenuScreen;\n\n/**\n * Created by Stijn on 30/01/2017.\n */\npublic class NamePrompt extend",
"end": 529,
"score": 0.9983975887298584,
"start": 524,
"tag": "NAME",
"value": "Stijn"
}
]
| null | []
| package nl.tudelft.ewi.f1manager.view.savelist;
import javafx.scene.Group;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import nl.tudelft.ewi.f1manager.controller.GameController;
import nl.tudelft.ewi.f1manager.view.F1Screen;
import nl.tudelft.ewi.f1manager.view.RenderThread;
import nl.tudelft.ewi.f1manager.view.menuscreens.MenuScreen;
/**
* Created by Stijn on 30/01/2017.
*/
public class NamePrompt extends Group {
private MenuScreen menuScreen;
private SaveGroup saveGroup;
private TextField textField;
/**
* A popup containing a textfield to insert the name of the save.
*
* @param menuScreen The screen the popup is on
* @param saveGroup The place to put the new save
*/
public NamePrompt(MenuScreen menuScreen, SaveGroup saveGroup) {
this.menuScreen = menuScreen;
this.saveGroup = saveGroup;
this.setLayoutX(0);
this.setLayoutY(0);
double screenHeight = F1Screen.getScreenHt();
double screenWidth = F1Screen.getScreenWd() - F1Screen.getMenuWd();
double promptHeight = screenHeight / 4;
double promptWidth = screenWidth / 4;
Text label = new Text("Team name:");
label.setWrappingWidth((promptWidth / 10) * 8);
textField = new TextField();
Rectangle background = new Rectangle();
double backgroundX = F1Screen.getMenuWd() + screenWidth / 2 - promptWidth / 2;
double backgroundY = screenHeight / 2 - promptHeight / 2;
background.setHeight(promptHeight);
background.setWidth(promptWidth);
background.setX(backgroundX);
background.setY(backgroundY);
background.setArcHeight(10);
background.setArcWidth(10);
background.setOpacity(0.7);
textField.setPrefWidth((promptWidth / 10) * 8);
textField.setLayoutX(backgroundX + promptWidth / 10);
textField.setLayoutY(screenHeight / 2 - promptHeight / 2 + promptHeight / 3);
textField.setPrefHeight(promptHeight / 3);
label.setLayoutX(backgroundX + promptWidth / 10);
label.setLayoutY(screenHeight / 2 - promptHeight / 2 + promptHeight / 3);
label.setFont(Font.font("Verdana", FontWeight.BOLD, 40));
Button confirm = new Button();
confirm.setText("Confirm");
confirm.setLayoutY(screenHeight / 2 - promptHeight / 2
+ (promptHeight / 3) * 2 + promptHeight / 12);
confirm.setLayoutX(backgroundX + promptWidth - promptWidth / 3 - promptWidth / 10);
confirm.setPrefHeight(promptHeight / 6);
confirm.setPrefWidth(promptWidth / 3);
confirm.setOnMouseClicked(new ConfirmMouseHandler(this));
confirm.setOnKeyPressed(new ConfirmKeyHandler(this));
Button cancel = new Button();
cancel.setText("Cancel");
cancel.setLayoutY(screenHeight / 2 - promptHeight / 2
+ (promptHeight / 3) * 2 + promptHeight / 12);
cancel.setLayoutX(backgroundX + promptWidth / 10);
cancel.setPrefHeight(promptHeight / 6);
cancel.setPrefWidth(promptWidth / 3);
cancel.setOnKeyPressed(new CancelKeyHandler(this));
cancel.setOnMouseClicked(new CancelMouseHandler(this));
this.getChildren().add(background);
this.getChildren().add(label);
this.getChildren().add(textField);
this.getChildren().add(confirm);
this.getChildren().add(cancel);
double labelY = screenHeight / 2 - promptHeight / 2
+ promptHeight / 3 - ((promptHeight / 3)
- label.getLayoutBounds().getHeight()) / 2;
double labelX = backgroundX + promptWidth / 10 + (promptWidth
- label.getLayoutBounds().getWidth()) / 4;
label.setLayoutY(labelY);
label.setLayoutX(labelX);
menuScreen.getChildren().add(this);
textField.requestFocus();
}
/**
* Confirms the name you put into the field.
*/
public void confirm() {
if (textField.getText() == null || textField.getText().equals("")) {
textField.setText("Nameless");
}
GameController.getGamecontrol().initTeam(textField.getText(), 200000000);
RenderThread.renderThread.switchToScreen("NewGameScreen");
remove();
}
public void remove() {
menuScreen.getChildren().remove(this);
}
}
| 4,535 | 0.654906 | 0.635281 | 122 | 36.172131 | 24.367975 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.663934 | false | false | 13 |
c39545a0b0d811231790a5fc345c0a2e5bd3e6b0 | 20,426,864,463,347 | 15a51a3ee841ec8ca5621d143c15936d15d9906f | /src/Invetory/Pool.java | 9d09556b8637c9a1d7fa199b00f83f119a6f0c26 | []
| no_license | bmoenga38/molle | https://github.com/bmoenga38/molle | 3d4c3d1839ee7b3a07685157ae6be152efdba28c | 3543fb23dd6395fb47018054ea17b5320f15983f | refs/heads/master | 2023-07-15T17:36:50.856000 | 2021-08-25T14:09:05 | 2021-08-25T14:09:05 | 399,839,395 | 0 | 0 | null | false | 2021-08-25T14:45:29 | 2021-08-25T14:00:06 | 2021-08-25T14:31:50 | 2021-08-25T14:45:28 | 0 | 0 | 0 | 0 | Java | false | false | package Invetory;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Pool {
Connection con;
String db_username;
String db_password;
String schema;
public Pool(String user, String pass){
this.db_username = user;
this.db_password = pass;
}
public Pool(String user, String pass,String db){
this.db_username = user;
this.db_password = pass;
this.schema = db;
}
public Connection connect() {
String db_url = "jdbc:mysql://127.0.0.1:3306/schema";
try {
con = DriverManager.getConnection(db_url,db_username,db_password);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return con;
}
public boolean connectTwo(){
String db_url = "jdbc:msql://127.0.0.1:3306/schema";
boolean connected = true;
try{
con = DriverManager.getConnection(db_url,db_username,db_password);
} catch (SQLException throwables) {
throwables.printStackTrace();
connected = false;
}
return connected;
}
}
| UTF-8 | Java | 1,176 | java | Pool.java | Java | [
{
"context": "tring user, String pass){\n this.db_username = user;\n this.db_password = pass;\n }\n\n public",
"end": 290,
"score": 0.970798671245575,
"start": 286,
"tag": "USERNAME",
"value": "user"
},
{
"context": " this.db_username = user;\n this.db_password = pass;\n }\n\n public Pool(String user, String pass,",
"end": 321,
"score": 0.9942723512649536,
"start": 317,
"tag": "PASSWORD",
"value": "pass"
},
{
"context": "String pass,String db){\n this.db_username = user;\n this.db_password = pass;\n this.sc",
"end": 414,
"score": 0.9558476209640503,
"start": 410,
"tag": "USERNAME",
"value": "user"
},
{
"context": "his.db_username = user;\n this.db_password = pass;\n this.schema = db;\n }\n public Conne",
"end": 447,
"score": 0.9976683259010315,
"start": 443,
"tag": "PASSWORD",
"value": "pass"
},
{
"context": "connect() {\n String db_url = \"jdbc:mysql://127.0.0.1:3306/schema\";\n try {\n con = Dri",
"end": 562,
"score": 0.9996832609176636,
"start": 553,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": "onnectTwo(){\n String db_url = \"jdbc:msql://127.0.0.1:3306/schema\";\n boolean connected = true;\n ",
"end": 871,
"score": 0.9996908903121948,
"start": 862,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
}
]
| null | []
| package Invetory;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Pool {
Connection con;
String db_username;
String db_password;
String schema;
public Pool(String user, String pass){
this.db_username = user;
this.db_password = <PASSWORD>;
}
public Pool(String user, String pass,String db){
this.db_username = user;
this.db_password = <PASSWORD>;
this.schema = db;
}
public Connection connect() {
String db_url = "jdbc:mysql://127.0.0.1:3306/schema";
try {
con = DriverManager.getConnection(db_url,db_username,db_password);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return con;
}
public boolean connectTwo(){
String db_url = "jdbc:msql://127.0.0.1:3306/schema";
boolean connected = true;
try{
con = DriverManager.getConnection(db_url,db_username,db_password);
} catch (SQLException throwables) {
throwables.printStackTrace();
connected = false;
}
return connected;
}
}
| 1,188 | 0.60034 | 0.583333 | 46 | 24.543478 | 19.949617 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.652174 | false | false | 13 |
d605705bb137fc63ad44e04ca09e416302773e83 | 20,633,022,898,745 | dfdb9cdb984db03d84f1aab081297e73e03dd19c | /raceahead_/src/com/raceahead_/profile.java | 9e4d7bf6c0b69da4811c33a499ba1180ffcea1e5 | []
| no_license | prashanth-artal/Race_Ahead_Eclipse | https://github.com/prashanth-artal/Race_Ahead_Eclipse | a7d9f1bb74a5ef368dca8c7bc720fb8215c82112 | 05c0ef77600e7d4c68cc13e5da77683c2cf6a9ff | refs/heads/master | 2021-01-01T05:45:30.152000 | 2016-05-26T23:23:05 | 2016-05-26T23:23:05 | 59,789,289 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.raceahead_;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
public class profile extends Activity implements OnClickListener{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profile);
ImageView homebutton = (ImageView)findViewById(R.id.homebutton4);
homebutton.setOnClickListener(this);
ImageView enterbutton = (ImageView)findViewById(R.id.enterbutton);
homebutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Intent intent = new Intent(
//profile.this,
//home.class
//);
//startActivity(intent);
finish();
}
});
enterbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
}
});
}
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId()==R.id.homebutton4)
startActivity(new Intent(this,home.class));
}
}
| UTF-8 | Java | 1,237 | java | profile.java | Java | []
| null | []
| package com.raceahead_;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
public class profile extends Activity implements OnClickListener{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profile);
ImageView homebutton = (ImageView)findViewById(R.id.homebutton4);
homebutton.setOnClickListener(this);
ImageView enterbutton = (ImageView)findViewById(R.id.enterbutton);
homebutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Intent intent = new Intent(
//profile.this,
//home.class
//);
//startActivity(intent);
finish();
}
});
enterbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
}
});
}
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId()==R.id.homebutton4)
startActivity(new Intent(this,home.class));
}
}
| 1,237 | 0.660469 | 0.658852 | 52 | 21.788462 | 21.642494 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.711538 | false | false | 13 |
3d8c6c5172a9f907ce3fa0c88749be9c866cb3d2 | 26,723,286,568,732 | 6e5c4b8a66260cfe8db66aa7138e78cb7a7ba14a | /src/DataStructures/Tree/Node.java | 16d3e16c1904ffb509c02470ca0d00fecdcb956d | []
| no_license | filmonghirmai/HackerRank-Solutions | https://github.com/filmonghirmai/HackerRank-Solutions | 1c8f5de4e0c0139013d1b41e027cc6ef81d4597f | dd1f46ecbcb73049c87c4f600a2b3c1c712609f7 | refs/heads/master | 2021-01-23T19:17:36.559000 | 2017-11-19T07:16:56 | 2017-11-19T07:16:56 | 102,818,013 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package DataStructures.Tree;
/**
* Author : Filmon Ghirmai
Github : github.com/filmonghirmai
HackerRank : hackerrank.com/skynet21
*
*/
import java.util.Scanner;
public class Node{
Node left,right;
int data;
Node(int data){
this.data=data;
left=right=null;
}
}
class Solution{
public static int getHeight(Node root){
//Write your code here
int height_Left = 0;
int height_Right = 0;
//if the root is null
if (root.left != null) {
height_Left = getHeight(root.left) + 1;
}
if (root.right != null) {
height_Right = getHeight(root.right) + 1;
}
return (height_Left > height_Right ? height_Left : height_Right);
}
public static Node insert(Node root,int data){
if(root == null){
return new Node(data);
}
else{
Node cur;
if(data <= root.data){
cur = insert(root.left,data);
root.left = cur;
}
else{
cur = insert(root.right,data);
root.right = cur;
}
return root;
}
}
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
Node root = null;
while(T-- > 0){
int data = sc.nextInt();
root = insert(root,data);
}
int height = getHeight(root);
System.out.println(height);
}
} | UTF-8 | Java | 1,536 | java | Node.java | Java | [
{
"context": "package DataStructures.Tree;\n/**\n * Author : Filmon Ghirmai\n Github : github.com/filmonghirmai\n HackerRan",
"end": 61,
"score": 0.999894380569458,
"start": 47,
"tag": "NAME",
"value": "Filmon Ghirmai"
},
{
"context": " Author : Filmon Ghirmai\n Github : github.com/filmonghirmai\n HackerRank : hackerrank.com/skynet21\n *\n */\n\nimp",
"end": 100,
"score": 0.9996479153633118,
"start": 87,
"tag": "USERNAME",
"value": "filmonghirmai"
}
]
| null | []
| package DataStructures.Tree;
/**
* Author : <NAME>
Github : github.com/filmonghirmai
HackerRank : hackerrank.com/skynet21
*
*/
import java.util.Scanner;
public class Node{
Node left,right;
int data;
Node(int data){
this.data=data;
left=right=null;
}
}
class Solution{
public static int getHeight(Node root){
//Write your code here
int height_Left = 0;
int height_Right = 0;
//if the root is null
if (root.left != null) {
height_Left = getHeight(root.left) + 1;
}
if (root.right != null) {
height_Right = getHeight(root.right) + 1;
}
return (height_Left > height_Right ? height_Left : height_Right);
}
public static Node insert(Node root,int data){
if(root == null){
return new Node(data);
}
else{
Node cur;
if(data <= root.data){
cur = insert(root.left,data);
root.left = cur;
}
else{
cur = insert(root.right,data);
root.right = cur;
}
return root;
}
}
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
Node root = null;
while(T-- > 0){
int data = sc.nextInt();
root = insert(root,data);
}
int height = getHeight(root);
System.out.println(height);
}
} | 1,528 | 0.502604 | 0.498047 | 64 | 23.015625 | 16.214859 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.46875 | false | false | 13 |
c2d6f92901e7f4eb82eecaeb52a6f8d4d83c8fca | 17,935,783,432,963 | 1415496f94592ba4412407b71dc18722598163dd | /doc/libjitisi/sources/javax/media/bean/playerbean/MediaPlayerVolumePropertyEditor.java | b43a64d5aad0318fab69505310f1706578de903f | [
"Apache-2.0"
]
| permissive | lhzheng880828/VOIPCall | https://github.com/lhzheng880828/VOIPCall | ad534535869c47b5fc17405b154bdc651b52651b | a7ba25debd4bd2086bae2a48306d28c614ce0d4a | refs/heads/master | 2021-07-04T17:25:21.953000 | 2020-09-29T07:29:42 | 2020-09-29T07:29:42 | 183,576,020 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package javax.media.bean.playerbean;
import java.beans.PropertyEditorSupport;
public class MediaPlayerVolumePropertyEditor extends PropertyEditorSupport {
public MediaPlayerVolumePropertyEditor() {
throw new UnsupportedOperationException();
}
public String getJavaInitializationString() {
throw new UnsupportedOperationException();
}
public String[] getTags() {
throw new UnsupportedOperationException();
}
}
| UTF-8 | Java | 461 | java | MediaPlayerVolumePropertyEditor.java | Java | []
| null | []
| package javax.media.bean.playerbean;
import java.beans.PropertyEditorSupport;
public class MediaPlayerVolumePropertyEditor extends PropertyEditorSupport {
public MediaPlayerVolumePropertyEditor() {
throw new UnsupportedOperationException();
}
public String getJavaInitializationString() {
throw new UnsupportedOperationException();
}
public String[] getTags() {
throw new UnsupportedOperationException();
}
}
| 461 | 0.744035 | 0.744035 | 17 | 26.117647 | 24.410418 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.294118 | false | false | 13 |
44cdd7f60ccf4faa05340f8f4f1523aa0a59494d | 28,484,223,174,630 | 7d0523596e53c2d2975b56e1dc973d686ab3aa3e | /p5_package/SimpleStackClass.java | f3ca8d1f095648423153c03beb44868d4d69cae6 | []
| no_license | AdamSchilperoort/CS249 | https://github.com/AdamSchilperoort/CS249 | 3c1928997a338226c44317edcac37b45f8b61640 | 07638725a7e784e9e8e3f17cd4e02b43129f3250 | refs/heads/master | 2022-12-11T19:45:06.903000 | 2020-09-10T22:56:05 | 2020-09-10T22:56:05 | 157,765,409 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package p5_package;
/**
*
* @author adamschilperoort
*/
public class SimpleStackClass
{
/**
* Provides constant for default capacity
*/
private final int DEFAULT_CAPACITY = 10;
/**
* Provides constant -999999 for access failure messaging
*/
public static final int FAILED_ACCESS = -999999;
/**
* Stores current capacity of stack class
*/
private int capacity;
/**
* Stores current size of stack class
*/
private int size;
/**
* Stores stack top index
*/
private int stackTopIndex;
/**
* Integer array stores stack data
*/
private int[] stackData;
/**
* Default constructor
*/
public SimpleStackClass()
{
capacity = DEFAULT_CAPACITY;
size = 0;
stackTopIndex = -1;
stackData = new int [ capacity ];
}
/**
* Initialization constructor
* @param capacitySetting - initial capacity of stackData class
*/
public SimpleStackClass(int capacitySetting)
{
capacity = capacitySetting;
size = 0;
stackTopIndex = -1;
stackData = new int [ capacity ];
}
/**
* Copy constructor
* @param copied - SimpleStackClass object to be copied
*/
public SimpleStackClass(SimpleStackClass copied)
{
capacity = copied.capacity;
size = copied.size;
stackTopIndex = copied.stackTopIndex;
stackData = new int [ capacity ];
stackData = copied.stackData;
}
/**
* Reports stack empty status
* <p>
* Note: Does not use if/else
* @return Boolean evidence of empty list
*/
public boolean isEmpty()
{
return ( size == 0 );
}
/**
* Checks for resize, then pushes value onto stack
* <p>
* Note: end of array is always the top of the stack;
* index is incremented and then value is appended to array
* @param newValue - Value to be pushed onto stack
*/
public void push(int newValue)
{
checkForReSize();
stackTopIndex++;
stackData[ size ] = newValue;
size++;
}
/**
* Removes and returns data from top of stack
* @return value if successful, FAILED_ACCESS if not
*/
public int pop()
{
if ( !isEmpty() )
{
stackTopIndex--;
size--;
return stackData[ stackTopIndex +1 ];
}
return FAILED_ACCESS;
}
/**
* provides peek at top of stack
* @return value if successful, FAILED_ACCESS if not
*/
public int peekTop()
{
if ( !isEmpty() )
{
return stackData[ stackTopIndex ];
}
return FAILED_ACCESS;
}
/**
* Checks for resize and resizes to twice the current capacity if needed
* <p>
* Note: Returns true if resize is necessary and is conducted;
* returns false if no action is taken
* @return success of operation
*/
private boolean checkForReSize()
{
int index;
if( size == capacity )
{
capacity *= 2;
int[] duplicateDoubleCapacity = new int[ capacity ];
for ( index = 0; index < size; index++ )
{
duplicateDoubleCapacity[ index ] = stackData [ index ];
}
stackData = duplicateDoubleCapacity;
return true;
}
return false;
}
/**
* Clears stack by setting size to zero and top index to negative one
*/
public void clear()
{
size = 0;
stackTopIndex = -1;
}
} | UTF-8 | Java | 3,865 | java | SimpleStackClass.java | Java | [
{
"context": "package p5_package;\n\n/**\n *\n * @author adamschilperoort\n */\npublic class SimpleStackClass\n {\n \n /",
"end": 55,
"score": 0.7955172061920166,
"start": 39,
"tag": "USERNAME",
"value": "adamschilperoort"
}
]
| null | []
| package p5_package;
/**
*
* @author adamschilperoort
*/
public class SimpleStackClass
{
/**
* Provides constant for default capacity
*/
private final int DEFAULT_CAPACITY = 10;
/**
* Provides constant -999999 for access failure messaging
*/
public static final int FAILED_ACCESS = -999999;
/**
* Stores current capacity of stack class
*/
private int capacity;
/**
* Stores current size of stack class
*/
private int size;
/**
* Stores stack top index
*/
private int stackTopIndex;
/**
* Integer array stores stack data
*/
private int[] stackData;
/**
* Default constructor
*/
public SimpleStackClass()
{
capacity = DEFAULT_CAPACITY;
size = 0;
stackTopIndex = -1;
stackData = new int [ capacity ];
}
/**
* Initialization constructor
* @param capacitySetting - initial capacity of stackData class
*/
public SimpleStackClass(int capacitySetting)
{
capacity = capacitySetting;
size = 0;
stackTopIndex = -1;
stackData = new int [ capacity ];
}
/**
* Copy constructor
* @param copied - SimpleStackClass object to be copied
*/
public SimpleStackClass(SimpleStackClass copied)
{
capacity = copied.capacity;
size = copied.size;
stackTopIndex = copied.stackTopIndex;
stackData = new int [ capacity ];
stackData = copied.stackData;
}
/**
* Reports stack empty status
* <p>
* Note: Does not use if/else
* @return Boolean evidence of empty list
*/
public boolean isEmpty()
{
return ( size == 0 );
}
/**
* Checks for resize, then pushes value onto stack
* <p>
* Note: end of array is always the top of the stack;
* index is incremented and then value is appended to array
* @param newValue - Value to be pushed onto stack
*/
public void push(int newValue)
{
checkForReSize();
stackTopIndex++;
stackData[ size ] = newValue;
size++;
}
/**
* Removes and returns data from top of stack
* @return value if successful, FAILED_ACCESS if not
*/
public int pop()
{
if ( !isEmpty() )
{
stackTopIndex--;
size--;
return stackData[ stackTopIndex +1 ];
}
return FAILED_ACCESS;
}
/**
* provides peek at top of stack
* @return value if successful, FAILED_ACCESS if not
*/
public int peekTop()
{
if ( !isEmpty() )
{
return stackData[ stackTopIndex ];
}
return FAILED_ACCESS;
}
/**
* Checks for resize and resizes to twice the current capacity if needed
* <p>
* Note: Returns true if resize is necessary and is conducted;
* returns false if no action is taken
* @return success of operation
*/
private boolean checkForReSize()
{
int index;
if( size == capacity )
{
capacity *= 2;
int[] duplicateDoubleCapacity = new int[ capacity ];
for ( index = 0; index < size; index++ )
{
duplicateDoubleCapacity[ index ] = stackData [ index ];
}
stackData = duplicateDoubleCapacity;
return true;
}
return false;
}
/**
* Clears stack by setting size to zero and top index to negative one
*/
public void clear()
{
size = 0;
stackTopIndex = -1;
}
} | 3,865 | 0.519276 | 0.512807 | 169 | 21.87574 | 18.473776 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.278107 | false | false | 13 |
fcb83943de646dfce3efdba0f3962ae88e37ca1f | 884,763,268,108 | e80dbcc31c92e91e011311a5bc4a00fdf09f8838 | /app/src/main/java/ca/louisechan/tokyo2020/Models/Attraction.java | cf7f97359e466b3afc3118a5eb59936410943307 | []
| no_license | lbchanjr/Tokyo-2020-Android | https://github.com/lbchanjr/Tokyo-2020-Android | 5c951bf8f4fffd9b350ac9807254da1f52e48a63 | c65e496e58baf83d3cff20552551f39d5e3265bb | refs/heads/master | 2022-12-04T11:19:30.415000 | 2020-08-23T03:25:05 | 2020-08-23T03:25:05 | 243,050,563 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ca.louisechan.tokyo2020.Models;
import androidx.annotation.NonNull;
import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.PrimaryKey;
@Entity(tableName = "attractions")
public class Attraction {
@PrimaryKey
private @NonNull String name;
private String address;
@ColumnInfo(name = "image_url")
private String imageUrl;
@ColumnInfo(name = "brief_desc")
private String briefDesc;
private String website;
@ColumnInfo(name = "youtube_url")
private String youtubeUrl;
@ColumnInfo(name = "detailed_desc")
private String detailedDesc;
@ColumnInfo(name = "visit_fee")
private Double visitFee;
public Attraction(@NonNull String name) {
this.name = name;
address = "";
imageUrl = "";
briefDesc = "";
website = "";
youtubeUrl = "";
detailedDesc = "";
visitFee = 0.0;
}
public @NonNull String getName() {
return name;
}
public void setName(@NonNull String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public String getBriefDesc() {
return briefDesc;
}
public void setBriefDesc(String briefDesc) {
this.briefDesc = briefDesc;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public String getYoutubeUrl() {
return youtubeUrl;
}
public void setYoutubeUrl(String youtubeUrl) {
this.youtubeUrl = youtubeUrl;
}
public String getDetailedDesc() {
return detailedDesc;
}
public void setDetailedDesc(String detailedDesc) {
this.detailedDesc = detailedDesc;
}
public Double getVisitFee() {
return visitFee;
}
public void setVisitFee(Double visitFee) {
this.visitFee = visitFee;
}
}
| UTF-8 | Java | 2,183 | java | Attraction.java | Java | []
| null | []
| package ca.louisechan.tokyo2020.Models;
import androidx.annotation.NonNull;
import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.PrimaryKey;
@Entity(tableName = "attractions")
public class Attraction {
@PrimaryKey
private @NonNull String name;
private String address;
@ColumnInfo(name = "image_url")
private String imageUrl;
@ColumnInfo(name = "brief_desc")
private String briefDesc;
private String website;
@ColumnInfo(name = "youtube_url")
private String youtubeUrl;
@ColumnInfo(name = "detailed_desc")
private String detailedDesc;
@ColumnInfo(name = "visit_fee")
private Double visitFee;
public Attraction(@NonNull String name) {
this.name = name;
address = "";
imageUrl = "";
briefDesc = "";
website = "";
youtubeUrl = "";
detailedDesc = "";
visitFee = 0.0;
}
public @NonNull String getName() {
return name;
}
public void setName(@NonNull String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public String getBriefDesc() {
return briefDesc;
}
public void setBriefDesc(String briefDesc) {
this.briefDesc = briefDesc;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public String getYoutubeUrl() {
return youtubeUrl;
}
public void setYoutubeUrl(String youtubeUrl) {
this.youtubeUrl = youtubeUrl;
}
public String getDetailedDesc() {
return detailedDesc;
}
public void setDetailedDesc(String detailedDesc) {
this.detailedDesc = detailedDesc;
}
public Double getVisitFee() {
return visitFee;
}
public void setVisitFee(Double visitFee) {
this.visitFee = visitFee;
}
}
| 2,183 | 0.622538 | 0.619789 | 99 | 21.050505 | 15.932543 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.373737 | false | false | 13 |
68b628f022d910c63516c60c8f09f4d3d653b764 | 21,569,325,824,498 | 1e747c845c6c7943db82149ab90f7670f98733b2 | /AndroidMobileApplications/04.Android Layouts/Tasks/src/Horoscope.java | def091617046043bd243bca8deed2d2341f4a0b6 | []
| no_license | Shoilev/Telerik-Academy | https://github.com/Shoilev/Telerik-Academy | 5d5db2d43ab60b70a3600dc19326f110799ba3e5 | c95ab2ae0584c562470dd3de4cf479c45eca67fe | refs/heads/master | 2020-05-31T14:29:03.667000 | 2014-12-06T22:20:14 | 2014-12-06T22:20:14 | 20,799,764 | 0 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
public class Horoscope {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Map<String, HoroscopeDetails> allHoroscopes;
public Horoscope(){
this.allHoroscopes = new HashMap<String, HoroscopeDetails>();
}
public void GetHoroscopeFrom(String url, String sign, Date targetDate) throws IOException, JSONException{
String date = dateFormat.format(targetDate);
String fullUrl = url + "sign=" + sign + "&date=" + date;
JSONObject json = JsonReader.readJsonFromUrl(fullUrl);
//System.out.println(json.toString());
//System.out.println(json.get("horoscope"));
//String currentSign = json.getJSONObject("horoscope").getString("sign");
//System.out.println(currentSign);
String currentHoroscope = json.getJSONObject("horoscope").getString("horoscope");
//System.out.println(currentHoroscope);
HoroscopeDetails currentHoroscopeDetails = this.allHoroscopes.get(sign) != null ? this.allHoroscopes.get(sign) : new HoroscopeDetails();
currentHoroscopeDetails.setDate(targetDate);
currentHoroscopeDetails.AddHoroscopes(currentHoroscope);
this.allHoroscopes.put(sign, currentHoroscopeDetails);
}
public Map<String, HoroscopeDetails> getAllHoroscopes() {
return allHoroscopes;
}
}
| UTF-8 | Java | 1,496 | java | Horoscope.java | Java | []
| null | []
| import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
public class Horoscope {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Map<String, HoroscopeDetails> allHoroscopes;
public Horoscope(){
this.allHoroscopes = new HashMap<String, HoroscopeDetails>();
}
public void GetHoroscopeFrom(String url, String sign, Date targetDate) throws IOException, JSONException{
String date = dateFormat.format(targetDate);
String fullUrl = url + "sign=" + sign + "&date=" + date;
JSONObject json = JsonReader.readJsonFromUrl(fullUrl);
//System.out.println(json.toString());
//System.out.println(json.get("horoscope"));
//String currentSign = json.getJSONObject("horoscope").getString("sign");
//System.out.println(currentSign);
String currentHoroscope = json.getJSONObject("horoscope").getString("horoscope");
//System.out.println(currentHoroscope);
HoroscopeDetails currentHoroscopeDetails = this.allHoroscopes.get(sign) != null ? this.allHoroscopes.get(sign) : new HoroscopeDetails();
currentHoroscopeDetails.setDate(targetDate);
currentHoroscopeDetails.AddHoroscopes(currentHoroscope);
this.allHoroscopes.put(sign, currentHoroscopeDetails);
}
public Map<String, HoroscopeDetails> getAllHoroscopes() {
return allHoroscopes;
}
}
| 1,496 | 0.741979 | 0.741979 | 44 | 33 | 32.29903 | 141 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.613636 | false | false | 13 |
014c099dec766ee6cdf18aec9c37cca767092b08 | 11,450,382,865,776 | a0423109d0dd871a0e5ae7be64c57afd062c3375 | /Aplicacion Movil/generated/bundles/login-transition/build/Android/Preview/app/src/main/java/com/foreign/Fuse/Drawing/GraphicsSurface.java | 99438c8f2ae55e6a15bd47c0d66814b90898cd9b | [
"Apache-2.0"
]
| permissive | marferfer/SpinOff-LoL | https://github.com/marferfer/SpinOff-LoL | 1c8a823302dac86133aa579d26ff90698bfc1ad6 | a9dba8ac9dd476ec1ef94712d9a8e76d3b45aca8 | refs/heads/master | 2020-03-29T20:09:20.322000 | 2018-10-09T10:19:33 | 2018-10-09T10:19:33 | 150,298,258 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.foreign.Fuse.Drawing;
// fuse defined imports
import com.uno.UnoObject;
import com.uno.BoolArray;
import com.uno.ByteArray;
import com.uno.CharArray;
import com.uno.DoubleArray;
import com.uno.FloatArray;
import com.uno.IntArray;
import com.uno.LongArray;
import com.uno.ObjectArray;
import com.uno.ShortArray;
import com.uno.StringArray;
import com.Bindings.UnoHelper;
import com.Bindings.UnoWrapped;
import com.Bindings.ExternedBlockHost;
// user defined imports
import android.graphics.Canvas;
import android.graphics.Bitmap;
import android.graphics.Shader;
import android.graphics.BitmapShader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Path;
import android.opengl.GLUtils;
import android.opengl.GLES20;
import android.graphics.Paint;
import android.graphics.LinearGradient;
import android.graphics.Shader.TileMode;
import android.graphics.Color;
import android.graphics.PorterDuffXfermode;
import android.graphics.Matrix;
import android.graphics.PorterDuff.Mode;
import com.fusetools.drawing.surface.LinearGradientStore;
import com.fusetools.drawing.surface.GraphicsSurfaceContext;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
public class GraphicsSurface
{
static void debug_log(Object message)
{
android.util.Log.d("LoginTransition", (message==null ? "null" : message.toString()));
}
public static void BeginImpl301(final Object _context,final int width,final int height,final int glTextureId)
{
GraphicsSurfaceContext context = (GraphicsSurfaceContext) _context;
context.width = width;
context.height = height;
context.glTextureId = glTextureId;
}
public static void EndImpl302(final Object context)
{
GraphicsSurfaceContext realContext = (GraphicsSurfaceContext) context;
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, realContext.glTextureId);
// heat up the caches. not needed but good to have
realContext.bitmap.prepareToDraw();
GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, realContext.bitmap, 0);
realContext.bitmap.recycle();
}
public static void LoadBitmap303(final Object context,final int width,final int height)
{
GraphicsSurfaceContext impl = (GraphicsSurfaceContext) context;
Bitmap b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = impl.canvas;
canvas.setBitmap(b);
impl.bitmap = b;
canvas.setMatrix(null);
// invert our bitmap since the Android canvas is inversed when drawing
canvas.translate(0.0f, (float)height);
canvas.scale(1, -1);
}
public static Object LoadImage304(final int glTextureId,final int width,final int height)
{
int size = width * height * 4;
int[] pixels = new int[size];
IntBuffer pixelData = IntBuffer.wrap(pixels);
GLES20.glPixelStorei(GLES20.GL_PACK_ALIGNMENT, 1);
GLES20.glReadPixels(0, 0, width,height, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, pixelData);
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
bitmap.copyPixelsFromBuffer(pixelData);
return bitmap;
}
}
| UTF-8 | Java | 3,425 | java | GraphicsSurface.java | Java | []
| null | []
| package com.foreign.Fuse.Drawing;
// fuse defined imports
import com.uno.UnoObject;
import com.uno.BoolArray;
import com.uno.ByteArray;
import com.uno.CharArray;
import com.uno.DoubleArray;
import com.uno.FloatArray;
import com.uno.IntArray;
import com.uno.LongArray;
import com.uno.ObjectArray;
import com.uno.ShortArray;
import com.uno.StringArray;
import com.Bindings.UnoHelper;
import com.Bindings.UnoWrapped;
import com.Bindings.ExternedBlockHost;
// user defined imports
import android.graphics.Canvas;
import android.graphics.Bitmap;
import android.graphics.Shader;
import android.graphics.BitmapShader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Path;
import android.opengl.GLUtils;
import android.opengl.GLES20;
import android.graphics.Paint;
import android.graphics.LinearGradient;
import android.graphics.Shader.TileMode;
import android.graphics.Color;
import android.graphics.PorterDuffXfermode;
import android.graphics.Matrix;
import android.graphics.PorterDuff.Mode;
import com.fusetools.drawing.surface.LinearGradientStore;
import com.fusetools.drawing.surface.GraphicsSurfaceContext;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
public class GraphicsSurface
{
static void debug_log(Object message)
{
android.util.Log.d("LoginTransition", (message==null ? "null" : message.toString()));
}
public static void BeginImpl301(final Object _context,final int width,final int height,final int glTextureId)
{
GraphicsSurfaceContext context = (GraphicsSurfaceContext) _context;
context.width = width;
context.height = height;
context.glTextureId = glTextureId;
}
public static void EndImpl302(final Object context)
{
GraphicsSurfaceContext realContext = (GraphicsSurfaceContext) context;
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, realContext.glTextureId);
// heat up the caches. not needed but good to have
realContext.bitmap.prepareToDraw();
GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, realContext.bitmap, 0);
realContext.bitmap.recycle();
}
public static void LoadBitmap303(final Object context,final int width,final int height)
{
GraphicsSurfaceContext impl = (GraphicsSurfaceContext) context;
Bitmap b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = impl.canvas;
canvas.setBitmap(b);
impl.bitmap = b;
canvas.setMatrix(null);
// invert our bitmap since the Android canvas is inversed when drawing
canvas.translate(0.0f, (float)height);
canvas.scale(1, -1);
}
public static Object LoadImage304(final int glTextureId,final int width,final int height)
{
int size = width * height * 4;
int[] pixels = new int[size];
IntBuffer pixelData = IntBuffer.wrap(pixels);
GLES20.glPixelStorei(GLES20.GL_PACK_ALIGNMENT, 1);
GLES20.glReadPixels(0, 0, width,height, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, pixelData);
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
bitmap.copyPixelsFromBuffer(pixelData);
return bitmap;
}
}
| 3,425 | 0.71708 | 0.70219 | 103 | 32.252426 | 25.352167 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.864078 | false | false | 13 |
9e23282390cb8dfa8c60a0d62125d26317bc4794 | 21,878,563,464,114 | 0c9e770519bbbf5d5f0d55955ae5163e33b6a39d | /app/src/main/java/com/zgld/mall/beans/AbstractYServiceChat.java | e68558002e3372536b3762206a30f43621c2f522 | []
| no_license | longliuping/ZgldStore | https://github.com/longliuping/ZgldStore | 6c4b3ee05b0b8db9739fb66154be2b1001219c88 | 8ba94ff4c5cb1a9f6436f7008f0bca0bb4868ac6 | refs/heads/master | 2021-01-21T13:48:06.839000 | 2016-05-12T09:41:38 | 2016-05-12T09:41:38 | 55,341,712 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.zgld.mall.beans;
import java.sql.Date;
/**
* AbstractYServiceChat entity provides the base persistence definition of the
* YServiceChat entity. @author MyEclipse Persistence Tools
*/
public abstract class AbstractYServiceChat implements java.io.Serializable {
// Fields
private Integer chatId;
private Integer accountId;
private String connectionId;
private String chatInfo;
private Integer isDelete;
private String chatTime;
// Constructors
/** default constructor */
public AbstractYServiceChat() {
}
/** minimal constructor */
public AbstractYServiceChat(String chatTime) {
this.chatTime = chatTime;
}
/** full constructor */
public AbstractYServiceChat(Integer accountId, String connectionId, String chatInfo, Integer isDelete, String chatTime) {
this.accountId = accountId;
this.connectionId = connectionId;
this.chatInfo = chatInfo;
this.isDelete = isDelete;
this.chatTime = chatTime;
}
// Property accessors
public Integer getChatId() {
return this.chatId;
}
public void setChatId(Integer chatId) {
this.chatId = chatId;
}
public Integer getAccountId() {
return this.accountId;
}
public void setAccountId(Integer accountId) {
this.accountId = accountId;
}
public String getConnectionId() {
return this.connectionId;
}
public void setConnectionId(String connectionId) {
this.connectionId = connectionId;
}
public String getChatInfo() {
return this.chatInfo;
}
public void setChatInfo(String chatInfo) {
this.chatInfo = chatInfo;
}
public Integer getIsDelete() {
return this.isDelete;
}
public void setIsDelete(Integer isDelete) {
this.isDelete = isDelete;
}
public String getChatTime() {
return this.chatTime;
}
public void setChatTime(String chatTime) {
this.chatTime = chatTime;
}
} | UTF-8 | Java | 1,806 | java | AbstractYServiceChat.java | Java | []
| null | []
| package com.zgld.mall.beans;
import java.sql.Date;
/**
* AbstractYServiceChat entity provides the base persistence definition of the
* YServiceChat entity. @author MyEclipse Persistence Tools
*/
public abstract class AbstractYServiceChat implements java.io.Serializable {
// Fields
private Integer chatId;
private Integer accountId;
private String connectionId;
private String chatInfo;
private Integer isDelete;
private String chatTime;
// Constructors
/** default constructor */
public AbstractYServiceChat() {
}
/** minimal constructor */
public AbstractYServiceChat(String chatTime) {
this.chatTime = chatTime;
}
/** full constructor */
public AbstractYServiceChat(Integer accountId, String connectionId, String chatInfo, Integer isDelete, String chatTime) {
this.accountId = accountId;
this.connectionId = connectionId;
this.chatInfo = chatInfo;
this.isDelete = isDelete;
this.chatTime = chatTime;
}
// Property accessors
public Integer getChatId() {
return this.chatId;
}
public void setChatId(Integer chatId) {
this.chatId = chatId;
}
public Integer getAccountId() {
return this.accountId;
}
public void setAccountId(Integer accountId) {
this.accountId = accountId;
}
public String getConnectionId() {
return this.connectionId;
}
public void setConnectionId(String connectionId) {
this.connectionId = connectionId;
}
public String getChatInfo() {
return this.chatInfo;
}
public void setChatInfo(String chatInfo) {
this.chatInfo = chatInfo;
}
public Integer getIsDelete() {
return this.isDelete;
}
public void setIsDelete(Integer isDelete) {
this.isDelete = isDelete;
}
public String getChatTime() {
return this.chatTime;
}
public void setChatTime(String chatTime) {
this.chatTime = chatTime;
}
} | 1,806 | 0.741971 | 0.741971 | 91 | 18.857143 | 21.012592 | 122 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.186813 | false | false | 13 |
06f54602bacb20aed505dcc6f17fccbcf80f62c3 | 21,878,563,461,356 | b7fcdcd99cec7d4a79345b99bb16f1a34d7bb950 | /src/main/java/com/paradigm/demo/service/ContentService.java | 1898371e6133c88f4085adbf365f4a8c018722b5 | []
| no_license | leopardv10/Insight-Engine-Demo | https://github.com/leopardv10/Insight-Engine-Demo | f9cc0ab2ba196854d8a37297f429282db1acb7a6 | 7f707fc0623f4e16c7ca40f31905b2875906cd67 | refs/heads/main | 2023-03-10T08:16:38.358000 | 2021-02-24T06:13:50 | 2021-02-24T06:13:50 | 341,803,955 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.paradigm.demo.service;
import com.paradigm.demo.dao.ContentDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class ContentService {
@Autowired
private ContentDao contentDao;
public void insert(int task_id, String file_name, String status) {
contentDao.init(task_id, file_name, status);
}
public void ocrUpdate(String text) {
contentDao.ocrUpdate(text);
}
public void finish(int task_id, String file_name, String status) { contentDao.finish(task_id, file_name, status); }
public String select(int task_id, String file_name) { return contentDao.getText(task_id, file_name); }
public void delete(int task_id) { contentDao.delete(task_id); }
}
| UTF-8 | Java | 755 | java | ContentService.java | Java | []
| null | []
| package com.paradigm.demo.service;
import com.paradigm.demo.dao.ContentDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class ContentService {
@Autowired
private ContentDao contentDao;
public void insert(int task_id, String file_name, String status) {
contentDao.init(task_id, file_name, status);
}
public void ocrUpdate(String text) {
contentDao.ocrUpdate(text);
}
public void finish(int task_id, String file_name, String status) { contentDao.finish(task_id, file_name, status); }
public String select(int task_id, String file_name) { return contentDao.getText(task_id, file_name); }
public void delete(int task_id) { contentDao.delete(task_id); }
}
| 755 | 0.762914 | 0.762914 | 27 | 26.962963 | 32.23695 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.222222 | false | false | 13 |
2daeb97cb2b0a6536d410fb58ad252fe23b7ed98 | 798,863,949,938 | a73906f406ae1d384c7b904fc86c1ff46da1bb53 | /src/Chapter1/Ex_1_3/ResizingArrayQueueOfStrings.java | b4d6dc6be346e543e040f1773ebcbd3d8bfa5d36 | []
| no_license | RagdollNoone/Algorithms4 | https://github.com/RagdollNoone/Algorithms4 | ccfdf83a5e2dd065300636c389fc0bc11a0038c8 | 23914dc0201f4dba31fdb7e2a167272eaafe7789 | refs/heads/master | 2020-03-18T16:39:08.992000 | 2019-09-02T09:03:14 | 2019-09-02T09:03:14 | 134,978,416 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Chapter1.Ex_1_3;
public class ResizingArrayQueueOfStrings<T> {
private T[] array;
private int N;
public ResizingArrayQueueOfStrings(int n) {
array = (T[])(new Object[n]);
N = 0;
}
public boolean isEmpty() {
return N == 0;
}
public int size() {
return N;
}
public T peek(){
return array[0];
}
public void enqueue(T object) {
array[++N] = object;
}
public T dequeue() {
T result = array[0];
for (int i = 1; i < N; i++) {
array[i - 1] = array[i];
}
array[N - 1] = null;
N--;
return result;
}
public void resize(int n) {
T[] newArray = (T[])(new Object[n]);
for (int i = 0; i < array.length; i++) {
newArray[i] = array[i];
}
array = newArray;
}
}
| UTF-8 | Java | 880 | java | ResizingArrayQueueOfStrings.java | Java | []
| null | []
| package Chapter1.Ex_1_3;
public class ResizingArrayQueueOfStrings<T> {
private T[] array;
private int N;
public ResizingArrayQueueOfStrings(int n) {
array = (T[])(new Object[n]);
N = 0;
}
public boolean isEmpty() {
return N == 0;
}
public int size() {
return N;
}
public T peek(){
return array[0];
}
public void enqueue(T object) {
array[++N] = object;
}
public T dequeue() {
T result = array[0];
for (int i = 1; i < N; i++) {
array[i - 1] = array[i];
}
array[N - 1] = null;
N--;
return result;
}
public void resize(int n) {
T[] newArray = (T[])(new Object[n]);
for (int i = 0; i < array.length; i++) {
newArray[i] = array[i];
}
array = newArray;
}
}
| 880 | 0.463636 | 0.451136 | 50 | 16.6 | 15.111585 | 48 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.42 | false | false | 13 |
4c2a65cee043924c2f0747ebe2b4aaec574d30d8 | 10,565,619,592,228 | 42a2312bceb92a963f9df6f3221025910b911cf1 | /familyServer/src/test/java/services/FillServiceTest.java | a3b950513827bc2aaef747398c8f296cf95ed33f | []
| no_license | franmah/familyMapServer | https://github.com/franmah/familyMapServer | 270f14f2abcfe2d1802873b3058552f73f28d50f | 9ad7a0e9d74b0cf269ba68fc93582b5b1653170c | refs/heads/master | 2023-07-20T06:22:38.634000 | 2023-07-08T16:56:39 | 2023-07-08T16:56:39 | 187,510,810 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package services;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import models.*;
import dao.OperationDAO;
import response.ErrorResponse;
import response.Response;
import response.SuccessResponse;
import static org.junit.Assert.*;
public class FillServiceTest {
@Before
public void setUp(){
OperationDAO db = new OperationDAO();
db.getUser_dao().deleteUsers();
db.getEvent_dao().deleteEvents();
db.getPerson_dao().deletePersons();
db.getAutToken_dao().deleteTokens();
db.commitAndCloseConnection(true);
}
@After
public void tearDown(){
OperationDAO db = new OperationDAO();
db.getEvent_dao().deleteEvents();
db.getPerson_dao().deletePersons();
db.getUser_dao().deleteUsers();
db.commitAndCloseConnection(true);
}
@Test
public void fillTreeCompleteTest(){
boolean success = true;
final String ANSWER = "Successfully generated 31 people and 91 event(s)";
try {
OperationDAO db = new OperationDAO();
db.getEvent_dao().deleteEvents();
db.getPerson_dao().deletePersons();
db.getUser_dao().deleteUsers();
User user = new User("test_user", "password", "email", "first", "last", "f", "test_person");
Person person = new Person("test_person", "test_user", "first", "last", "f");
db.getUser_dao().addUser(user);
db.getPerson_dao().addPerson(person);
db.commitAndCloseConnection(true);
FillService service = new FillService();
Response response = service.fillUserTree("test_user", 4);
if(response instanceof SuccessResponse){
success = true;
assertEquals(ANSWER, response.toString());
}
if(response instanceof ErrorResponse){
success = false;
}
}
catch (Exception e){
System.out.println(e.toString());
e.printStackTrace();
success = false;
}
assertTrue(success);
}
@Test
public void fillTreeWrongUser(){
boolean success = true;
final String ANSWER = "Successfully generated 31 people and 91 event(s)";
try {
OperationDAO db = new OperationDAO();
db.getEvent_dao().deleteEvents();
db.getPerson_dao().deletePersons();
db.getUser_dao().deleteUsers();
User user = new User("test_user", "password", "email", "first", "last", "f", "test_person");
Person person = new Person("test_person", "test_user", "first", "last", "f");
db.getUser_dao().addUser(user);
db.getPerson_dao().addPerson(person);
db.commitAndCloseConnection(true);
FillService service = new FillService();
Response response = service.fillUserTree("wrong_user", 4);
if(response instanceof SuccessResponse){
success = false;
assertEquals(ANSWER, response.toString());
}
if(response instanceof ErrorResponse){
success = true;
}
}
catch (Exception e){
System.out.println(e.toString());
e.printStackTrace();
success = true;
}
assertTrue(success);
}
}
| UTF-8 | Java | 3,416 | java | FillServiceTest.java | Java | [
{
"context": "deleteUsers();\n\n User user = new User(\"test_user\", \"password\", \"email\", \"first\", \"last\", \"f\", \"tes",
"end": 1265,
"score": 0.978287398815155,
"start": 1256,
"tag": "USERNAME",
"value": "test_user"
},
{
"context": "deleteUsers();\n\n User user = new User(\"test_user\", \"password\", \"email\", \"first\", \"last\", \"f\", \"tes",
"end": 2543,
"score": 0.9960713982582092,
"start": 2534,
"tag": "USERNAME",
"value": "test_user"
}
]
| null | []
| package services;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import models.*;
import dao.OperationDAO;
import response.ErrorResponse;
import response.Response;
import response.SuccessResponse;
import static org.junit.Assert.*;
public class FillServiceTest {
@Before
public void setUp(){
OperationDAO db = new OperationDAO();
db.getUser_dao().deleteUsers();
db.getEvent_dao().deleteEvents();
db.getPerson_dao().deletePersons();
db.getAutToken_dao().deleteTokens();
db.commitAndCloseConnection(true);
}
@After
public void tearDown(){
OperationDAO db = new OperationDAO();
db.getEvent_dao().deleteEvents();
db.getPerson_dao().deletePersons();
db.getUser_dao().deleteUsers();
db.commitAndCloseConnection(true);
}
@Test
public void fillTreeCompleteTest(){
boolean success = true;
final String ANSWER = "Successfully generated 31 people and 91 event(s)";
try {
OperationDAO db = new OperationDAO();
db.getEvent_dao().deleteEvents();
db.getPerson_dao().deletePersons();
db.getUser_dao().deleteUsers();
User user = new User("test_user", "password", "email", "first", "last", "f", "test_person");
Person person = new Person("test_person", "test_user", "first", "last", "f");
db.getUser_dao().addUser(user);
db.getPerson_dao().addPerson(person);
db.commitAndCloseConnection(true);
FillService service = new FillService();
Response response = service.fillUserTree("test_user", 4);
if(response instanceof SuccessResponse){
success = true;
assertEquals(ANSWER, response.toString());
}
if(response instanceof ErrorResponse){
success = false;
}
}
catch (Exception e){
System.out.println(e.toString());
e.printStackTrace();
success = false;
}
assertTrue(success);
}
@Test
public void fillTreeWrongUser(){
boolean success = true;
final String ANSWER = "Successfully generated 31 people and 91 event(s)";
try {
OperationDAO db = new OperationDAO();
db.getEvent_dao().deleteEvents();
db.getPerson_dao().deletePersons();
db.getUser_dao().deleteUsers();
User user = new User("test_user", "password", "email", "first", "last", "f", "test_person");
Person person = new Person("test_person", "test_user", "first", "last", "f");
db.getUser_dao().addUser(user);
db.getPerson_dao().addPerson(person);
db.commitAndCloseConnection(true);
FillService service = new FillService();
Response response = service.fillUserTree("wrong_user", 4);
if(response instanceof SuccessResponse){
success = false;
assertEquals(ANSWER, response.toString());
}
if(response instanceof ErrorResponse){
success = true;
}
}
catch (Exception e){
System.out.println(e.toString());
e.printStackTrace();
success = true;
}
assertTrue(success);
}
}
| 3,416 | 0.570843 | 0.567916 | 112 | 29.5 | 23.994047 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.758929 | false | false | 13 |
dcdd7999c9fc66d146c12bfef8126d7b89c620d6 | 5,652,176,982,787 | 1e3a3d88cde3f88874f59da5dc90017bbbe68779 | /ProblemSolving/src/com/jilani/trees/summation/FindSumOfMaxDepthNodes.java | c2a99d9a3049207bed8c0e46f96a9d0d248a24f2 | []
| no_license | shaikji/algorithms | https://github.com/shaikji/algorithms | 84c950a86b509e1ebf5cf137f51fc76e175f023b | f09e42e143baba55ef8392f55ad95e9d61e43eff | refs/heads/master | 2020-11-24T12:39:47.894000 | 2020-07-29T02:15:34 | 2020-07-29T02:15:34 | 228,145,769 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.jilani.trees.summation;
public class FindSumOfMaxDepthNodes {
public static void main(String[] args) {
root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(6);
root.right.right = new Node(7);
System.out.println(" Sum = " + maxDepthNodesSum(root));
mxdepth(root,0);
System.out.println(" sum = " + sum );
}
static int max_level = Integer.MIN_VALUE;
static int sum = 0;
static void mxdepth(Node root, int level) {
if (root == null)
return;
if ( level > max_level) {
sum = root.data;
max_level = level;
} else if ( level == max_level) {
sum += root.data;
}
mxdepth(root.left, level+1);
mxdepth(root.right, level + 1);
}
static int maxDepthNodesSum(Node root) {
if (root == null)
return 0;
int maxDepth = maxDepth(root);
return sumNodes(root, maxDepth);
}
static int sumNodes(Node root, int max) {
if ( root == null)
return 0;
if ( max == 1) {
return root.data;
}
return sumNodes(root.left, max-1) + sumNodes(root.right, max-1);
}
static int maxDepth(Node root) {
if ( root == null)
return 0;
int ld = maxDepth(root.left);
int rd = maxDepth(root.right);
return 1 + Math.max(ld, rd);
}
static Node root;
static class Node {
int data;
Node left;
Node right;
Node(int data) {
this.data = data;
}
}
}
| UTF-8 | Java | 1,476 | java | FindSumOfMaxDepthNodes.java | Java | []
| null | []
| package com.jilani.trees.summation;
public class FindSumOfMaxDepthNodes {
public static void main(String[] args) {
root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(6);
root.right.right = new Node(7);
System.out.println(" Sum = " + maxDepthNodesSum(root));
mxdepth(root,0);
System.out.println(" sum = " + sum );
}
static int max_level = Integer.MIN_VALUE;
static int sum = 0;
static void mxdepth(Node root, int level) {
if (root == null)
return;
if ( level > max_level) {
sum = root.data;
max_level = level;
} else if ( level == max_level) {
sum += root.data;
}
mxdepth(root.left, level+1);
mxdepth(root.right, level + 1);
}
static int maxDepthNodesSum(Node root) {
if (root == null)
return 0;
int maxDepth = maxDepth(root);
return sumNodes(root, maxDepth);
}
static int sumNodes(Node root, int max) {
if ( root == null)
return 0;
if ( max == 1) {
return root.data;
}
return sumNodes(root.left, max-1) + sumNodes(root.right, max-1);
}
static int maxDepth(Node root) {
if ( root == null)
return 0;
int ld = maxDepth(root.left);
int rd = maxDepth(root.right);
return 1 + Math.max(ld, rd);
}
static Node root;
static class Node {
int data;
Node left;
Node right;
Node(int data) {
this.data = data;
}
}
}
| 1,476 | 0.605691 | 0.593496 | 85 | 16.364706 | 15.539587 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.152941 | false | false | 13 |
c4874c8a3eda4764f1d6a547b6f0910f8da6ab46 | 31,619,549,260,377 | ac9afc4cf3efb2a8b42a67bfad88fbae220a535b | /src/main/java/uk/gov/dwp/jsa/officesearch/service/controllers/OfficeSearchController.java | efd41c74b62f80b125fdb4680987ff462c04dd3b | [
"ISC",
"LicenseRef-scancode-proprietary-license"
]
| permissive | dwp/nsjsa-office-search-service | https://github.com/dwp/nsjsa-office-search-service | f744eacae0fab0024915464f227be087cd6a65ae | efc38399b5fc40047a032bb86d0a196db0e22805 | refs/heads/master | 2023-02-27T11:27:34.722000 | 2022-02-25T19:37:29 | 2022-02-25T19:37:29 | 238,942,636 | 0 | 1 | ISC | false | 2023-02-20T18:22:26 | 2020-02-07T14:23:36 | 2022-01-13T09:59:40 | 2023-02-20T18:22:25 | 67 | 0 | 2 | 7 | Java | false | false | package uk.gov.dwp.jsa.officesearch.service.controllers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import uk.gov.dwp.jsa.officesearch.service.config.WithVersionUriComponentsBuilder;
import uk.gov.dwp.jsa.officesearch.service.models.http.BenefitCentreResponse;
import uk.gov.dwp.jsa.officesearch.service.models.http.JobCentreResponse;
import uk.gov.dwp.jsa.officesearch.service.models.http.api.ApiResponse;
import uk.gov.dwp.jsa.officesearch.service.services.OfficeSearchService;
import uk.gov.dwp.jsa.officesearch.service.services.ResponseBuilder;
import javax.servlet.http.HttpServletRequest;
import java.net.URI;
@RestController
@RequestMapping("/nsjsa/" + WithVersionUriComponentsBuilder.VERSION_SPEL + "/office/job-centre")
public class OfficeSearchController {
private static final Logger LOGGER = LoggerFactory.getLogger(OfficeSearchController.class);
private final OfficeSearchService officeSearchService;
@Autowired
public OfficeSearchController(final OfficeSearchService officeSearchService) {
this.officeSearchService = officeSearchService;
}
@GetMapping("/postcode/{postcode}")
public ResponseEntity<ApiResponse<JobCentreResponse>> getJobCentreForPostcode(
@PathVariable("postcode") final String postcode,
final HttpServletRequest request
) {
LOGGER.debug("Getting job centre for postcode: {}", postcode);
JobCentreResponse jobCentreResponse = officeSearchService
.getJobCentreForPostcode(postcode)
.orElse(null);
return generateResponse(
request.getRequestURI(),
jobCentreResponse
);
}
@GetMapping(value = "{id}")
public ResponseEntity<ApiResponse<JobCentreResponse>> getJobCentreForId(
@PathVariable final Long id,
final HttpServletRequest request
) {
LOGGER.debug("Getting job centre for id: {}", id);
JobCentreResponse jobCentreResponse = officeSearchService
.getJobCentreForId(id)
.orElse(null);
return generateResponse(
request.getRequestURI(),
jobCentreResponse
);
}
@GetMapping("/{id}/benefit-centre")
public ResponseEntity<ApiResponse<BenefitCentreResponse>> getBenefitCentreByJobCentreId(
@PathVariable final Long id,
final HttpServletRequest request
) {
LOGGER.debug("Getting benefit centre for job centre id: {}", id);
BenefitCentreResponse benefitCentreResponse = officeSearchService
.getBenefitCentreByJobCentreId(id)
.orElse(null);
return generateResponse(
request.getRequestURI(),
benefitCentreResponse
);
}
private <T> ResponseEntity<ApiResponse<T>> generateResponse(final String path, final T objectToReturn) {
if (objectToReturn == null) {
LOGGER.error("Error no object found in path {}", path);
return buildErrorResponse();
} else {
return buildSuccessfulResponse(
path,
objectToReturn,
HttpStatus.OK
);
}
}
private <T> ResponseEntity<ApiResponse<T>> buildSuccessfulResponse(
final String path,
final T objectToReturn,
final HttpStatus status
) {
return new ResponseBuilder<T>()
.withStatus(status)
.withSuccessData(URI.create(path), objectToReturn)
.build();
}
private <T> ResponseEntity<ApiResponse<T>> buildErrorResponse() {
return new ResponseBuilder<T>()
.withStatus(HttpStatus.NOT_FOUND)
.withApiError(HttpStatus.NOT_FOUND.toString(), HttpStatus.NOT_FOUND.getReasonPhrase())
.build();
}
}
| UTF-8 | Java | 4,304 | java | OfficeSearchController.java | Java | []
| null | []
| package uk.gov.dwp.jsa.officesearch.service.controllers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import uk.gov.dwp.jsa.officesearch.service.config.WithVersionUriComponentsBuilder;
import uk.gov.dwp.jsa.officesearch.service.models.http.BenefitCentreResponse;
import uk.gov.dwp.jsa.officesearch.service.models.http.JobCentreResponse;
import uk.gov.dwp.jsa.officesearch.service.models.http.api.ApiResponse;
import uk.gov.dwp.jsa.officesearch.service.services.OfficeSearchService;
import uk.gov.dwp.jsa.officesearch.service.services.ResponseBuilder;
import javax.servlet.http.HttpServletRequest;
import java.net.URI;
@RestController
@RequestMapping("/nsjsa/" + WithVersionUriComponentsBuilder.VERSION_SPEL + "/office/job-centre")
public class OfficeSearchController {
private static final Logger LOGGER = LoggerFactory.getLogger(OfficeSearchController.class);
private final OfficeSearchService officeSearchService;
@Autowired
public OfficeSearchController(final OfficeSearchService officeSearchService) {
this.officeSearchService = officeSearchService;
}
@GetMapping("/postcode/{postcode}")
public ResponseEntity<ApiResponse<JobCentreResponse>> getJobCentreForPostcode(
@PathVariable("postcode") final String postcode,
final HttpServletRequest request
) {
LOGGER.debug("Getting job centre for postcode: {}", postcode);
JobCentreResponse jobCentreResponse = officeSearchService
.getJobCentreForPostcode(postcode)
.orElse(null);
return generateResponse(
request.getRequestURI(),
jobCentreResponse
);
}
@GetMapping(value = "{id}")
public ResponseEntity<ApiResponse<JobCentreResponse>> getJobCentreForId(
@PathVariable final Long id,
final HttpServletRequest request
) {
LOGGER.debug("Getting job centre for id: {}", id);
JobCentreResponse jobCentreResponse = officeSearchService
.getJobCentreForId(id)
.orElse(null);
return generateResponse(
request.getRequestURI(),
jobCentreResponse
);
}
@GetMapping("/{id}/benefit-centre")
public ResponseEntity<ApiResponse<BenefitCentreResponse>> getBenefitCentreByJobCentreId(
@PathVariable final Long id,
final HttpServletRequest request
) {
LOGGER.debug("Getting benefit centre for job centre id: {}", id);
BenefitCentreResponse benefitCentreResponse = officeSearchService
.getBenefitCentreByJobCentreId(id)
.orElse(null);
return generateResponse(
request.getRequestURI(),
benefitCentreResponse
);
}
private <T> ResponseEntity<ApiResponse<T>> generateResponse(final String path, final T objectToReturn) {
if (objectToReturn == null) {
LOGGER.error("Error no object found in path {}", path);
return buildErrorResponse();
} else {
return buildSuccessfulResponse(
path,
objectToReturn,
HttpStatus.OK
);
}
}
private <T> ResponseEntity<ApiResponse<T>> buildSuccessfulResponse(
final String path,
final T objectToReturn,
final HttpStatus status
) {
return new ResponseBuilder<T>()
.withStatus(status)
.withSuccessData(URI.create(path), objectToReturn)
.build();
}
private <T> ResponseEntity<ApiResponse<T>> buildErrorResponse() {
return new ResponseBuilder<T>()
.withStatus(HttpStatus.NOT_FOUND)
.withApiError(HttpStatus.NOT_FOUND.toString(), HttpStatus.NOT_FOUND.getReasonPhrase())
.build();
}
}
| 4,304 | 0.677974 | 0.677509 | 116 | 36.103447 | 27.990263 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.448276 | false | false | 13 |
78264447a0f0a1dbc3c7d7ff1d3ad1dcca042380 | 8,022,998,977,807 | 750bb6c6fa115fde1bfe646bb3359f886373d24e | /src/test/java/enw/ENW042.java | f97e91ff518a3c830277cde042723ea4c5b1827e | []
| no_license | Basha692/BashaSelenium | https://github.com/Basha692/BashaSelenium | d21e2c7abd5f9a5d7c3be43578863186f2f7322f | 37fb79f85e6c973610b14b53d3e14b6183219a41 | refs/heads/master | 2022-07-13T11:05:59.156000 | 2019-12-06T06:08:37 | 2019-12-06T06:08:37 | 226,252,795 | 0 | 0 | null | false | 2022-06-29T17:49:37 | 2019-12-06T05:30:40 | 2019-12-06T06:09:16 | 2022-06-29T17:49:36 | 9,007 | 0 | 0 | 6 | Java | false | false | package enw;
import java.io.PrintWriter;
import java.io.StringWriter;
import org.openqa.selenium.By;
import org.testng.Assert;
import org.testng.SkipException;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import com.relevantcodes.extentreports.LogStatus;
import base.TestBase;
import util.BrowserWaits;
import util.ErrorUtil;
import util.ExtentManager;
import util.OnePObjectMap;
//Verify that the user signed in to community enabled version of Endnote and having valid Neon
//session will be taken to Profile page seamlessly by clicking on the profilename in profile flyout
// Verify that the user signed in to community enabled version of Endnote and having valid Neon session
//will be taken to Account page seamlessly by clicking on the Account in profile flyout
public class ENW042 extends TestBase {
static int status = 1;
String expectedUrl = "https://dev-stable.1p.thomsonreuters.com/#/profile/";
@BeforeTest
public void beforeTest() throws Exception {
extent = ExtentManager.getReporter(filePath);
rowData = testcase.get(this.getClass().getSimpleName());
test = extent.startTest(rowData.getTestcaseId(), rowData.getTestcaseDescription()).assignCategory("ENW");
}
@Test
public void testcaseENW042() throws Exception {
boolean testRunmode = getTestRunMode(rowData.getTestcaseRunmode());
boolean master_condition = suiteRunmode && testRunmode;
if (!master_condition) {
test.log(LogStatus.SKIP,
"Skipping test case " + this.getClass().getSimpleName() + " as the run mode is set to NO");
throw new SkipException("Skipping Test Case" + this.getClass().getSimpleName() + " as runmode set to NO");// reports
}
test.log(LogStatus.INFO, this.getClass().getSimpleName() + " execution starts--->");
try {
openBrowser();
maximizeWindow();
clearCookies();
ob.get(host + CONFIG.getProperty("appendENWAppUrl"));
pf.getOnboardingModalsPageInstance(ob).ENWSTeamLogin(LOGIN.getProperty("MarketUser42"),
(LOGIN.getProperty("MarketUser42PWD")));
BrowserWaits.waitTime(6);
pf.getBrowserWaitsInstance(ob).waitUntilElementIsClickable(OnePObjectMap.ENW_HEADER_XPATH);
String actual_result = pf.getBrowserActionInstance(ob).getElement(OnePObjectMap.ENW_HEADER_XPATH).getText();
logger.info("Header Text displayed as:" + actual_result);
logger.info("Actual result displayed as :" + actual_result
+ " text without the hot link and not allow user to Navigate to Neon");
pf.getBrowserWaitsInstance(ob).waitUntilElementIsClickable(OnePObjectMap.ENW_PROFILE_USER_ICON_XPATH);
jsClick(ob, ob.findElement(By.xpath(OnePObjectMap.ENW_PROFILE_USER_ICON_XPATH.toString())));
BrowserWaits.waitTime(3);
jsClick(ob, ob.findElement(By.xpath(OnePObjectMap.IMAGE_USER_XPATH.toString())));
BrowserWaits.waitTime(8);
if (ob.getCurrentUrl().contains(expectedUrl)) {
if (!ob.findElement(By.xpath(OR.getProperty("searchBox_textBox"))).isDisplayed()) {
test.log(LogStatus.FAIL, "Expected page is not displayed");
Assert.assertEquals(true, false);
} else {
test.log(LogStatus.PASS, "Neon Home page is displayed and Navigating to the proper Page.");
}
} else {
test.log(LogStatus.FAIL, "Neon Home page is not displayed");
}
ob.navigate().refresh();
BrowserWaits.waitTime(2);
//NavigateToENW();
logout();
closeBrowser();
test.log(LogStatus.INFO, this.getClass().getSimpleName() + " execution ends--->");
} catch (Throwable t) {
test.log(LogStatus.FAIL, "Something unexpected happened");// extent
// reports
// next 3 lines to print whole testng error in report
StringWriter errors = new StringWriter();
t.printStackTrace(new PrintWriter(errors));
test.log(LogStatus.INFO, errors.toString());// extent reports
ErrorUtil.addVerificationFailure(t);// testng
test.log(LogStatus.INFO, "Snapshot below: " + test.addScreenCapture(
captureScreenshot(this.getClass().getSimpleName() + "_something_unexpected_happened")));// screenshot
closeBrowser();
}
}
private void NavigateToENW() throws Exception {
String expected_uRL= "https://dev-stable.1p.thomsonreuters.com/#/account?app=endnote";
BrowserWaits.waitTime(5);
jsClick(ob, ob.findElement(By.xpath("//span[@class='ng-binding']")));
// BrowserWaits.waitTime(2);
// jsClick(ob, ob.findElement(By.cssSelector("a[href='/#/bridge?app=endnote']")));
// ob.get(host + CONFIG.getProperty("appendENWAppUrl"));
// ob.navigate().refresh();
// pf.getOnboardingModalsPageInstance(ob).ENWSTeamLogin(LOGIN.getProperty("MarketUser42"),(LOGIN.getProperty("MarketUser42PWD")));
BrowserWaits.waitTime(10);
// try {
// if (ob.findElements(By.xpath(OnePObjectMap.ENW_HOME_CONTINUE_XPATH.toString())).size() != 0) {
// ob.findElement(By.xpath(OnePObjectMap.ENW_HOME_CONTINUE_XPATH.toString())).click();
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
pf.getBrowserWaitsInstance(ob).waitUntilElementIsClickable(OnePObjectMap.ENW_PROFILE_USER_ICON_XPATH);
jsClick(ob, ob.findElement(By.xpath(OnePObjectMap.ENW_PROFILE_USER_ICON_XPATH.toString())));
BrowserWaits.waitTime(3);
jsClick(ob, ob.findElement(By.cssSelector(OnePObjectMap.ENW_PROFILE_USER_ACCOUNT_LINK_CSS.toString())));
BrowserWaits.waitTime(8);
waitForElementTobeClickable(ob, By.cssSelector(OnePObjectMap.HOME_PROJECT_NEON_PROFILE_IMAGE_CSS.toString()), 180);
String actualEmail = ob.findElement(By.xpath(OnePObjectMap.ACCOUNT_ACTUAL_EMAIL_XPATH.toString())).getText();
System.out.println(actualEmail);
try {
Assert.assertEquals(ob.getCurrentUrl(), expected_uRL);
Assert.assertEquals(LOGIN.getProperty("MarketUser42"), actualEmail);
test.log(LogStatus.PASS, " Email id getting displayed in Neon Account Setting page is correct");
}
catch (Throwable t) {
test.log(LogStatus.FAIL, "Email id getting displayed in Neon Account Setting page is incorrect");// extent
// reports
status = 2;// excel
test.log(LogStatus.INFO, "Snapshot below: " + test.addScreenCapture(captureScreenshot(this.getClass()
.getSimpleName()
+ "_more_search_results_do_not_get_displayed_when_user_scrolls_down_in_ALL_search_results_page")));// screenshot
ErrorUtil.addVerificationFailure(t);
}
}
@AfterTest
public void reportTestResult() {
extent.endTest(test);
}
}
| UTF-8 | Java | 6,372 | java | ENW042.java | Java | []
| null | []
| package enw;
import java.io.PrintWriter;
import java.io.StringWriter;
import org.openqa.selenium.By;
import org.testng.Assert;
import org.testng.SkipException;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import com.relevantcodes.extentreports.LogStatus;
import base.TestBase;
import util.BrowserWaits;
import util.ErrorUtil;
import util.ExtentManager;
import util.OnePObjectMap;
//Verify that the user signed in to community enabled version of Endnote and having valid Neon
//session will be taken to Profile page seamlessly by clicking on the profilename in profile flyout
// Verify that the user signed in to community enabled version of Endnote and having valid Neon session
//will be taken to Account page seamlessly by clicking on the Account in profile flyout
public class ENW042 extends TestBase {
static int status = 1;
String expectedUrl = "https://dev-stable.1p.thomsonreuters.com/#/profile/";
@BeforeTest
public void beforeTest() throws Exception {
extent = ExtentManager.getReporter(filePath);
rowData = testcase.get(this.getClass().getSimpleName());
test = extent.startTest(rowData.getTestcaseId(), rowData.getTestcaseDescription()).assignCategory("ENW");
}
@Test
public void testcaseENW042() throws Exception {
boolean testRunmode = getTestRunMode(rowData.getTestcaseRunmode());
boolean master_condition = suiteRunmode && testRunmode;
if (!master_condition) {
test.log(LogStatus.SKIP,
"Skipping test case " + this.getClass().getSimpleName() + " as the run mode is set to NO");
throw new SkipException("Skipping Test Case" + this.getClass().getSimpleName() + " as runmode set to NO");// reports
}
test.log(LogStatus.INFO, this.getClass().getSimpleName() + " execution starts--->");
try {
openBrowser();
maximizeWindow();
clearCookies();
ob.get(host + CONFIG.getProperty("appendENWAppUrl"));
pf.getOnboardingModalsPageInstance(ob).ENWSTeamLogin(LOGIN.getProperty("MarketUser42"),
(LOGIN.getProperty("MarketUser42PWD")));
BrowserWaits.waitTime(6);
pf.getBrowserWaitsInstance(ob).waitUntilElementIsClickable(OnePObjectMap.ENW_HEADER_XPATH);
String actual_result = pf.getBrowserActionInstance(ob).getElement(OnePObjectMap.ENW_HEADER_XPATH).getText();
logger.info("Header Text displayed as:" + actual_result);
logger.info("Actual result displayed as :" + actual_result
+ " text without the hot link and not allow user to Navigate to Neon");
pf.getBrowserWaitsInstance(ob).waitUntilElementIsClickable(OnePObjectMap.ENW_PROFILE_USER_ICON_XPATH);
jsClick(ob, ob.findElement(By.xpath(OnePObjectMap.ENW_PROFILE_USER_ICON_XPATH.toString())));
BrowserWaits.waitTime(3);
jsClick(ob, ob.findElement(By.xpath(OnePObjectMap.IMAGE_USER_XPATH.toString())));
BrowserWaits.waitTime(8);
if (ob.getCurrentUrl().contains(expectedUrl)) {
if (!ob.findElement(By.xpath(OR.getProperty("searchBox_textBox"))).isDisplayed()) {
test.log(LogStatus.FAIL, "Expected page is not displayed");
Assert.assertEquals(true, false);
} else {
test.log(LogStatus.PASS, "Neon Home page is displayed and Navigating to the proper Page.");
}
} else {
test.log(LogStatus.FAIL, "Neon Home page is not displayed");
}
ob.navigate().refresh();
BrowserWaits.waitTime(2);
//NavigateToENW();
logout();
closeBrowser();
test.log(LogStatus.INFO, this.getClass().getSimpleName() + " execution ends--->");
} catch (Throwable t) {
test.log(LogStatus.FAIL, "Something unexpected happened");// extent
// reports
// next 3 lines to print whole testng error in report
StringWriter errors = new StringWriter();
t.printStackTrace(new PrintWriter(errors));
test.log(LogStatus.INFO, errors.toString());// extent reports
ErrorUtil.addVerificationFailure(t);// testng
test.log(LogStatus.INFO, "Snapshot below: " + test.addScreenCapture(
captureScreenshot(this.getClass().getSimpleName() + "_something_unexpected_happened")));// screenshot
closeBrowser();
}
}
private void NavigateToENW() throws Exception {
String expected_uRL= "https://dev-stable.1p.thomsonreuters.com/#/account?app=endnote";
BrowserWaits.waitTime(5);
jsClick(ob, ob.findElement(By.xpath("//span[@class='ng-binding']")));
// BrowserWaits.waitTime(2);
// jsClick(ob, ob.findElement(By.cssSelector("a[href='/#/bridge?app=endnote']")));
// ob.get(host + CONFIG.getProperty("appendENWAppUrl"));
// ob.navigate().refresh();
// pf.getOnboardingModalsPageInstance(ob).ENWSTeamLogin(LOGIN.getProperty("MarketUser42"),(LOGIN.getProperty("MarketUser42PWD")));
BrowserWaits.waitTime(10);
// try {
// if (ob.findElements(By.xpath(OnePObjectMap.ENW_HOME_CONTINUE_XPATH.toString())).size() != 0) {
// ob.findElement(By.xpath(OnePObjectMap.ENW_HOME_CONTINUE_XPATH.toString())).click();
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
pf.getBrowserWaitsInstance(ob).waitUntilElementIsClickable(OnePObjectMap.ENW_PROFILE_USER_ICON_XPATH);
jsClick(ob, ob.findElement(By.xpath(OnePObjectMap.ENW_PROFILE_USER_ICON_XPATH.toString())));
BrowserWaits.waitTime(3);
jsClick(ob, ob.findElement(By.cssSelector(OnePObjectMap.ENW_PROFILE_USER_ACCOUNT_LINK_CSS.toString())));
BrowserWaits.waitTime(8);
waitForElementTobeClickable(ob, By.cssSelector(OnePObjectMap.HOME_PROJECT_NEON_PROFILE_IMAGE_CSS.toString()), 180);
String actualEmail = ob.findElement(By.xpath(OnePObjectMap.ACCOUNT_ACTUAL_EMAIL_XPATH.toString())).getText();
System.out.println(actualEmail);
try {
Assert.assertEquals(ob.getCurrentUrl(), expected_uRL);
Assert.assertEquals(LOGIN.getProperty("MarketUser42"), actualEmail);
test.log(LogStatus.PASS, " Email id getting displayed in Neon Account Setting page is correct");
}
catch (Throwable t) {
test.log(LogStatus.FAIL, "Email id getting displayed in Neon Account Setting page is incorrect");// extent
// reports
status = 2;// excel
test.log(LogStatus.INFO, "Snapshot below: " + test.addScreenCapture(captureScreenshot(this.getClass()
.getSimpleName()
+ "_more_search_results_do_not_get_displayed_when_user_scrolls_down_in_ALL_search_results_page")));// screenshot
ErrorUtil.addVerificationFailure(t);
}
}
@AfterTest
public void reportTestResult() {
extent.endTest(test);
}
}
| 6,372 | 0.736817 | 0.731325 | 144 | 43.25 | 36.187302 | 131 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.888889 | false | false | 13 |
51c7a804fff0b87009e7333dea109986cde739ea | 16,930,761,098,650 | 3124f829a4118ed567acde94fb991e551648ac95 | /src/main/java/de/devsurf/common/lang/search/TypedFinder.java | a91ba1e4931ede36d6b6410c949cac78d6c3c974 | [
"Apache-2.0"
]
| permissive | manzke/common-lang | https://github.com/manzke/common-lang | 172b0065c6d3056791f9b3e0abd1f7a017e507af | 379ac5c6bd537b4399e15947bdebe1462b7d1e07 | refs/heads/master | 2016-09-06T21:35:45.063000 | 2013-10-17T15:08:47 | 2013-10-17T15:08:47 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
Copyright 2013 Daniel Manzke (devsurf)
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 de.devsurf.common.lang.search;
import java.util.Map;
public interface TypedFinder<Type> {
TypedFinder<Type> with( Map<DescriptorField, Object> keyValues )
throws SearchException;
TypedFinder<Type> with( DescriptorField field, Object value )
throws SearchException;
TypedFinder<Type> combinedBy( QueryOperator op );
TypedResult<Type> result()
throws SearchException;
}
| UTF-8 | Java | 1,025 | java | TypedFinder.java | Java | [
{
"context": "/*\r\nCopyright 2013 Daniel Manzke (devsurf)\r\n\r\nLicensed under the Apache License, V",
"end": 32,
"score": 0.9998193383216858,
"start": 19,
"tag": "NAME",
"value": "Daniel Manzke"
}
]
| null | []
| /*
Copyright 2013 <NAME> (devsurf)
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 de.devsurf.common.lang.search;
import java.util.Map;
public interface TypedFinder<Type> {
TypedFinder<Type> with( Map<DescriptorField, Object> keyValues )
throws SearchException;
TypedFinder<Type> with( DescriptorField field, Object value )
throws SearchException;
TypedFinder<Type> combinedBy( QueryOperator op );
TypedResult<Type> result()
throws SearchException;
}
| 1,018 | 0.734634 | 0.726829 | 32 | 30.03125 | 26.344454 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.40625 | false | false | 13 |
332ce973e004f2105bfaa58743de76849a32554c | 27,908,697,549,046 | 6a3ca49d1f0f67de76c3fee2fe0ad712e03c1094 | /HW1-RobotAttack/src/RobotAttackApp.java | 3b4ff52582a4e498b1076c2d65ee5da01c4bea67 | []
| no_license | renbergmack/ArtificialIntelligence | https://github.com/renbergmack/ArtificialIntelligence | 2f7d79fb0f8913719db7889d4caad9c58563113e | a10f7e2b886d7d9d2c271cebc7750ff5c03e644e | refs/heads/master | 2021-05-07T04:48:36.665000 | 2017-11-21T02:05:10 | 2017-11-21T02:05:10 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.io.*;
import java.util.Scanner;
public class RobotAttackApp {
public static void main(String[] args){
//Objects - Robot and player
Robot player = new Robot();
Robot computer = new Robot();
//Variables
String L;
String R;
String P;
String userData;
userData = userInput.nextLine();
while (!player.isDisabled() && !computer.isDisabled()) {
System.out.println("<L>aser attack, <R>ocket attack, or <P>Power up? ");
Scanner userInput = new Scanner(System.in);
if (userData.equals("L")) {
if (player.laserAttack(computer) == true){
System.out.println("Player hits computer with laser");
}
else {
System.out.println("Player misses computer with laser");
}
}
else if (userData.equals("R")) {
if (player.laserAttack(computer) == true){
System.out.println("Player hits computer with Rocket");
}
else {
System.out.println("Player misses computer with Rocket");
}
}
else if (userData.equals("P")) {
player.powerUp();
System.out.println("Player powers up");
}
else {
System.out.println("Must type a letter L, R, or P");
}
System.out.println("Player's robot is " + player.getCurrentStatus());
System.out.println("Computer's robot is " + computer.getCurrentStatus());
if (player.isDisabled()) {
System.out.println("The computer destroyed your robot");
}
else if (computer.isDisabled()) {
System.out.println("You destroyed the robot!");
}
}
}
}
| UTF-8 | Java | 1,523 | java | RobotAttackApp.java | Java | []
| null | []
| import java.io.*;
import java.util.Scanner;
public class RobotAttackApp {
public static void main(String[] args){
//Objects - Robot and player
Robot player = new Robot();
Robot computer = new Robot();
//Variables
String L;
String R;
String P;
String userData;
userData = userInput.nextLine();
while (!player.isDisabled() && !computer.isDisabled()) {
System.out.println("<L>aser attack, <R>ocket attack, or <P>Power up? ");
Scanner userInput = new Scanner(System.in);
if (userData.equals("L")) {
if (player.laserAttack(computer) == true){
System.out.println("Player hits computer with laser");
}
else {
System.out.println("Player misses computer with laser");
}
}
else if (userData.equals("R")) {
if (player.laserAttack(computer) == true){
System.out.println("Player hits computer with Rocket");
}
else {
System.out.println("Player misses computer with Rocket");
}
}
else if (userData.equals("P")) {
player.powerUp();
System.out.println("Player powers up");
}
else {
System.out.println("Must type a letter L, R, or P");
}
System.out.println("Player's robot is " + player.getCurrentStatus());
System.out.println("Computer's robot is " + computer.getCurrentStatus());
if (player.isDisabled()) {
System.out.println("The computer destroyed your robot");
}
else if (computer.isDisabled()) {
System.out.println("You destroyed the robot!");
}
}
}
}
| 1,523 | 0.630991 | 0.630991 | 61 | 23.950819 | 22.892784 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.213115 | false | false | 13 |
e3b498a3e4ab1cb5546f55886de9ead31ef2ea62 | 3,238,405,402,346 | 4a2fb92eb9b815b34e5ba0a3fe34b5982e232dd8 | /crawlers/CrawlerTelegramBot/src/main/java/br/com/idwall/desafio/cli/subreddit/thread/IdwallFindSubredditThread.java | f65272486da5d5dee9a73aeb9318b21be9ad9bd7 | []
| no_license | YuriCordeiro/desafios | https://github.com/YuriCordeiro/desafios | c14ec0d45bbcdb5553ce13a7a04ce8fbc5a2b890 | d4a34566a7530dc1fb9829580423adaa2b0c27f3 | refs/heads/master | 2021-01-24T22:44:07.920000 | 2018-03-05T20:22:19 | 2018-03-05T20:22:19 | 123,281,895 | 0 | 0 | null | true | 2018-02-28T12:27:46 | 2018-02-28T12:27:46 | 2018-02-28T06:22:10 | 2018-02-06T16:12:26 | 19 | 0 | 0 | 0 | null | false | null | package br.com.idwall.desafio.cli.subreddit.thread;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import br.com.idwall.desafio.model.SubredditThread;
import br.com.idwall.desafio.utils.PropertiesUtil;
/**
* Simple class that should provides the top threads of subreddits given, found
* on <a href="http://www.reddit.com">Reddit's Web-site</a>
*
* @author Yuri Cordeiro
*
*/
public class IdwallFindSubredditThread extends FindSubredditThread {
/**
* Find a single subreddit info</br>
* It ever appends the StringBuilder using an empty map, reducing the final
* StringBuilder length
*/
@Override
public String getSubredditInfo(String subreddit) {
HashMap<String, List<SubredditThread>> singleSubredditHash = new HashMap<>();
findWebSubredditThreadInformation(subreddit, singleSubredditHash);
return printResults(singleSubredditHash);
}
@Override
public void endDriverSession() {
getDriver().quit();
}
/**
* Build a StringBuilder object with all the subreddit's thread results
*
* @param subredditThreadHash
* A hashmap containing subreddits(key) and threads list(value)
* @return a String with all the subreddit's thread results
*/
private String printResults(HashMap<String, List<SubredditThread>> subredditThreadHash) {
StringBuilder sbThreadsResults = new StringBuilder();
if (subredditThreadHash.size() > 0) {
// For each hasmap key (String)..
subredditThreadHash.entrySet().stream().forEach(entry -> {
sbThreadsResults.append(
"\n~> Showing top rated threads for *" + entry.getKey().toUpperCase() + "* subreddit on "
+ PropertiesUtil.getBundleMessage("url.base_url").replace("/r", "").replace("www.", "")
+ "\n|");
if (entry.getValue().size() > 0) {
// list all the values(List<SubredditThread>)
entry.getValue().stream()
.forEach(threadObject -> sbThreadsResults.append("\n*Thread Title*: "
+ threadObject.getTitle() + "\n*Thread Upvotes*: " + threadObject.getUpVotes()
+ "\n*Thread Link*: [" + threadObject.getThreadLink() + "]" + "\n*Comments Link*: ["
+ threadObject.getCommentsLink() + "]\n\n"));
} else {
sbThreadsResults
.append("\n=== No threads with " + PropertiesUtil.getBundleMessage("param.minimum_upvotes")
+ "+ upvotes were found for this subreddit===\n");
}
sbThreadsResults.append("|\n|.: End of *" + entry.getKey().toUpperCase() + "* subreddit threads\n\n\n");
});
}
return sbThreadsResults.toString();
}
/**
* Searches for a subreddit top threads information
*
* @param subreddit
* <reddit it's a forum website, where> subreddits are sub-forums,
* like <b>cats</b>
* @return a hash containing the subreddit keys, and a list of top threads
*/
public Map<String, List<SubredditThread>> findWebSubredditThreadInformation(String subreddit,
HashMap<String, List<SubredditThread>> threadsHash) {
// Will contain all threads found
List<SubredditThread> threadsList = new ArrayList<>();
// Will contain all the <div> elements with the class name 'thing'
List<WebElement> webElementsThreadsList = null;
try {
getDriver().get(PropertiesUtil.getBundleMessage("url.base_url").concat(subreddit)
.concat(PropertiesUtil.getBundleMessage("url.top"))
.concat(PropertiesUtil.getBundleMessage("url.limit_param")));
} catch (Exception e) {
System.out.println("Url not found: " + e);
}
try {
webElementsThreadsList = getDriver().findElements(By.className("thing"));
} catch (Exception e) {
System.out.println(PropertiesUtil.getBundleMessage("cli_err.thing_class_not_found") + e);
}
System.out.println("\n(" + webElementsThreadsList.size() + ") " + subreddit + " threads were found.");
System.out.println("I'm filtering the top rated.. It may take a minute..\n");
webElementsThreadsList.stream().forEach(thingClassWebElement -> {
// Verify if it's a promoted thread, 'cuz we don't want to have it
if (!getSubredditThreadService().isPromotedThread(thingClassWebElement)) {
SubredditThread subredditThread = getSubredditThreadService()
.findSubredditThreadInformations(thingClassWebElement, subreddit);
if (subredditThread.getUpVotes() != null) {
threadsList.add(subredditThread);
System.out.println("\nYeah!! Now I got " + threadsList.size() + " top rated thread(s).");
} else {
System.out.println("\nIt isn't a top rated thread..");
}
}
});
if (threadsList.size() > 0) {
threadsHash.put(subreddit, threadsList);
} else {
threadsHash.put(subreddit, new ArrayList<>());
}
return threadsHash;
}
}
| UTF-8 | Java | 4,774 | java | IdwallFindSubredditThread.java | Java | [
{
"context": "w.reddit.com\">Reddit's Web-site</a>\n * \n * @author Yuri Cordeiro\n *\n */\npublic class IdwallFindSubredditThread ext",
"end": 500,
"score": 0.9998895525932312,
"start": 487,
"tag": "NAME",
"value": "Yuri Cordeiro"
}
]
| null | []
| package br.com.idwall.desafio.cli.subreddit.thread;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import br.com.idwall.desafio.model.SubredditThread;
import br.com.idwall.desafio.utils.PropertiesUtil;
/**
* Simple class that should provides the top threads of subreddits given, found
* on <a href="http://www.reddit.com">Reddit's Web-site</a>
*
* @author <NAME>
*
*/
public class IdwallFindSubredditThread extends FindSubredditThread {
/**
* Find a single subreddit info</br>
* It ever appends the StringBuilder using an empty map, reducing the final
* StringBuilder length
*/
@Override
public String getSubredditInfo(String subreddit) {
HashMap<String, List<SubredditThread>> singleSubredditHash = new HashMap<>();
findWebSubredditThreadInformation(subreddit, singleSubredditHash);
return printResults(singleSubredditHash);
}
@Override
public void endDriverSession() {
getDriver().quit();
}
/**
* Build a StringBuilder object with all the subreddit's thread results
*
* @param subredditThreadHash
* A hashmap containing subreddits(key) and threads list(value)
* @return a String with all the subreddit's thread results
*/
private String printResults(HashMap<String, List<SubredditThread>> subredditThreadHash) {
StringBuilder sbThreadsResults = new StringBuilder();
if (subredditThreadHash.size() > 0) {
// For each hasmap key (String)..
subredditThreadHash.entrySet().stream().forEach(entry -> {
sbThreadsResults.append(
"\n~> Showing top rated threads for *" + entry.getKey().toUpperCase() + "* subreddit on "
+ PropertiesUtil.getBundleMessage("url.base_url").replace("/r", "").replace("www.", "")
+ "\n|");
if (entry.getValue().size() > 0) {
// list all the values(List<SubredditThread>)
entry.getValue().stream()
.forEach(threadObject -> sbThreadsResults.append("\n*Thread Title*: "
+ threadObject.getTitle() + "\n*Thread Upvotes*: " + threadObject.getUpVotes()
+ "\n*Thread Link*: [" + threadObject.getThreadLink() + "]" + "\n*Comments Link*: ["
+ threadObject.getCommentsLink() + "]\n\n"));
} else {
sbThreadsResults
.append("\n=== No threads with " + PropertiesUtil.getBundleMessage("param.minimum_upvotes")
+ "+ upvotes were found for this subreddit===\n");
}
sbThreadsResults.append("|\n|.: End of *" + entry.getKey().toUpperCase() + "* subreddit threads\n\n\n");
});
}
return sbThreadsResults.toString();
}
/**
* Searches for a subreddit top threads information
*
* @param subreddit
* <reddit it's a forum website, where> subreddits are sub-forums,
* like <b>cats</b>
* @return a hash containing the subreddit keys, and a list of top threads
*/
public Map<String, List<SubredditThread>> findWebSubredditThreadInformation(String subreddit,
HashMap<String, List<SubredditThread>> threadsHash) {
// Will contain all threads found
List<SubredditThread> threadsList = new ArrayList<>();
// Will contain all the <div> elements with the class name 'thing'
List<WebElement> webElementsThreadsList = null;
try {
getDriver().get(PropertiesUtil.getBundleMessage("url.base_url").concat(subreddit)
.concat(PropertiesUtil.getBundleMessage("url.top"))
.concat(PropertiesUtil.getBundleMessage("url.limit_param")));
} catch (Exception e) {
System.out.println("Url not found: " + e);
}
try {
webElementsThreadsList = getDriver().findElements(By.className("thing"));
} catch (Exception e) {
System.out.println(PropertiesUtil.getBundleMessage("cli_err.thing_class_not_found") + e);
}
System.out.println("\n(" + webElementsThreadsList.size() + ") " + subreddit + " threads were found.");
System.out.println("I'm filtering the top rated.. It may take a minute..\n");
webElementsThreadsList.stream().forEach(thingClassWebElement -> {
// Verify if it's a promoted thread, 'cuz we don't want to have it
if (!getSubredditThreadService().isPromotedThread(thingClassWebElement)) {
SubredditThread subredditThread = getSubredditThreadService()
.findSubredditThreadInformations(thingClassWebElement, subreddit);
if (subredditThread.getUpVotes() != null) {
threadsList.add(subredditThread);
System.out.println("\nYeah!! Now I got " + threadsList.size() + " top rated thread(s).");
} else {
System.out.println("\nIt isn't a top rated thread..");
}
}
});
if (threadsList.size() > 0) {
threadsHash.put(subreddit, threadsList);
} else {
threadsHash.put(subreddit, new ArrayList<>());
}
return threadsHash;
}
}
| 4,767 | 0.691663 | 0.691035 | 138 | 33.594204 | 31.847153 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.398551 | false | false | 13 |
3082e995010aef48cdf3e08a0af572cb8241b0bf | 23,613,730,198,679 | 1fa82ce3a5645019ee33883bcb954468615a3ab0 | /src/main/java/com/vehiclecontacting/utils/RedisUtils.java | 704b62afe1759feaae1b4767ae57972ec6e449d9 | []
| no_license | ez-leetcode/VehicleContacting | https://github.com/ez-leetcode/VehicleContacting | 3a69451bda25e03d413a0742a2d7cb5903ca0767 | 5838c627962da9759f571e442f43f5b50a1b947b | refs/heads/master | 2023-05-19T15:53:01.432000 | 2021-06-11T15:13:20 | 2021-06-11T15:13:20 | 367,365,238 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.vehiclecontacting.utils;
import com.google.common.base.Charsets;
import com.google.common.base.Preconditions;
import com.google.common.hash.Funnel;
import com.vehiclecontacting.config.BloomFilterConfig;
import com.vehiclecontacting.mapper.UserMapper;
import com.vehiclecontacting.pojo.User;
import io.jsonwebtoken.Claims;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component;
import java.util.*;
import java.util.concurrent.TimeUnit;
@Setter
@Getter
@Component
@Slf4j
public class RedisUtils {
@Autowired
private StringRedisTemplate redisTemplate;
@Autowired
private UserMapper userMapper;
//次数加1
public void addKeyByTime(String key,int hours){
//防止雪崩,加随机时间
String value = redisTemplate.opsForValue().get(key);
Random random = new Random();
long second = hours * 3600L + random.nextInt(100);
int cnt = 0;
if(value != null){
cnt = Integer.parseInt(value);
}
cnt ++;
//存入redis
redisTemplate.opsForValue().set(key,String.valueOf(cnt),second,TimeUnit.SECONDS);
}
//次数减1
public void subKeyByTime(String key,int hours){
//这里不会雪崩就不加随机时间了
String value = redisTemplate.opsForValue().get(key);
int cnt = 0;
if(value != null){
cnt = Integer.parseInt(value);
}
cnt --;
//存入redis
redisTemplate.opsForValue().set(key,String.valueOf(cnt),hours * 3600L,TimeUnit.SECONDS);
}
//存带有过期时间的key-value
public void saveByHoursTime(String key,String value,int hours){
//为防止缓存雪崩 加一个随机时间
Random random = new Random();
long second = hours * 3600L + random.nextInt(100);
redisTemplate.opsForValue().set(key,value,second,TimeUnit.SECONDS);
}
public void saveByMinutesTime(String key,String value,int minutes){
//为防止缓存雪崩 加一个随机时间
Random random = new Random();
long second = minutes * 60L + random.nextInt(25);
redisTemplate.opsForValue().set(key,value,second,TimeUnit.SECONDS);
}
//重置时间
public void resetExpire(String key,String value,int minutes){
//为防止缓存雪崩,加一个随机时间
Random random = new Random();
long seconds = minutes * 60L + random.nextInt(25);
redisTemplate.opsForValue().set(key,value,seconds,TimeUnit.SECONDS);
}
//判断key是否存在
public boolean hasKey(String key){
return redisTemplate.opsForValue().get(key) != null;
}
//删除key
public void delete(String key){
redisTemplate.delete(key);
}
//获取value
public String getValue(String key){
return redisTemplate.opsForValue().get(key);
}
//判断key是否在这个时间后
public boolean isAfterDate(String key,int minutes){
return redisTemplate.getExpire(key,TimeUnit.SECONDS) > (long) minutes * 60;
}
//从token中获取身份信息
public UsernamePasswordAuthenticationToken getAuthentication(String token){
//先解析token
Claims claims = JwtUtils.getTokenBody(token);
//获取用户名
String username = claims.getId();
//根据用户名判断是否为管理员,后面可根据
User user = userMapper.selectById(username);
Collection<GrantedAuthority> authList = new ArrayList<>();
authList.add(new SimpleGrantedAuthority("ROLE_USER"));
if(user == null){
log.error("用户不存在");
return null;
}
/*
if(user.getIsAdministrator() == 0){
//用户不是管理员
log.info("身份认证成功,用户:" + username + "是普通用户");
return new UsernamePasswordAuthenticationToken(new org.springframework.security.core.userdetails.User(username,user.getPassword(),authList),token,authList);
}else{
authList.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
}
log.info("身份认证成功,用户:" + username + "是管理员");
*/
return new UsernamePasswordAuthenticationToken(new org.springframework.security.core.userdetails.User(username,user.getPassword(),authList),token,authList);
}
public Map<Long,Integer> getAllScan(){
Map<Long,Integer> map = new HashMap<>();
Set<String> scanSet = redisTemplate.keys("scan_*");
if(scanSet != null){
//有需要更新的浏览量
for(String x:scanSet){
//获取次数
String value = redisTemplate.opsForValue().get(x);
if(value != null){
//存入map
map.put(Long.parseLong(x.substring(x.lastIndexOf("_") + 1)),Integer.parseInt(value));
}
}
}
log.info("需要增加浏览量的数据:" + map.toString());
return map;
}
public Map<Long,Integer> getAllLike(){
Map<Long,Integer> map = new HashMap<>();
Set<String> likeSet = redisTemplate.keys("cntLike_*");
if(likeSet != null){
//有点赞
for(String x:likeSet){
//获取次数
String value = redisTemplate.opsForValue().get(x);
if(value != null){
//存入map
map.put(Long.parseLong(x.substring(x.lastIndexOf("_") + 1)),Integer.parseInt(value));
}
}
}else{
log.info("8小时内暂时没有点赞信息");
}
log.info("8小时内点赞信息:" + map.toString());
return map;
}
public Map<Long,Integer> getAllFavor(){
Map<Long,Integer> map = new HashMap<>();
Set<String> favorSet = redisTemplate.keys("cntFavor_*");
if(favorSet != null){
//有新收藏
for(String x:favorSet){
//获取次数
String value = redisTemplate.opsForValue().get(x);
if(value != null){
//存入map
map.put(Long.parseLong(x.substring(x.lastIndexOf("_") + 1)),Integer.parseInt(value));
}
}
}else{
log.info("8小时内没有收藏信息");
}
log.info("8小时内收藏信息:" + map.toString());
return map;
}
public Map<String,Integer> getAllHotKeyword(){
Map<String,Integer> map = new HashMap<>();
Set<String> hotKeywordSet = redisTemplate.keys("hotKeyword_*");
if(hotKeywordSet != null){
//有新热词
for(String x:hotKeywordSet){
//获取次数
String value = redisTemplate.opsForValue().get(x);
if(value != null){
//存入map
map.put(x.substring(x.lastIndexOf("_") + 1),Integer.parseInt(value));
}
}
}else{
log.info("8小时内没有热词信息");
}
log.info("8小时内热词信息:" + map.toString());
return map;
}
/**
* 根据给定的布隆过滤器添加值
*/
public <T> void addByBloomFilter(BloomFilterConfig<T> bloomFilterHelper, String key, T value) {
Preconditions.checkArgument(bloomFilterHelper != null, "bloomFilterHelper不能为空");
int[] offset = bloomFilterHelper.murmurHashOffset(value);
for (int i : offset) {
System.out.println("key : " + key + " " + "value : " + i);
redisTemplate.opsForValue().setBit(key, i, true);
}
}
/**
* 根据给定的布隆过滤器判断值是否存在
*/
public <T> boolean includeByBloomFilter(BloomFilterConfig<T> bloomFilterHelper, String key, T value) {
Preconditions.checkArgument(bloomFilterHelper != null, "bloomFilterHelper不能为空");
int[] offset = bloomFilterHelper.murmurHashOffset(value);
for (int i : offset) {
System.out.println("key : " + key + " " + "value : " + i);
if (!redisTemplate.opsForValue().getBit(key, i)) {
return false;
}
}
return true;
}
@Bean
public BloomFilterConfig<String> initBloomFilterHelper() {
return new BloomFilterConfig<>((Funnel<String>) (from, into) -> into.putString(from, Charsets.UTF_8).putString(from, Charsets.UTF_8), 1000000, 0.01);
}
}
| UTF-8 | Java | 9,050 | java | RedisUtils.java | Java | [
{
"context": "\n log.info(\"身份认证成功,用户:\" + username + \"是普通用户\");\n return new UsernamePasswordAuthent",
"end": 3986,
"score": 0.954754114151001,
"start": 3982,
"tag": "USERNAME",
"value": "普通用户"
}
]
| null | []
| package com.vehiclecontacting.utils;
import com.google.common.base.Charsets;
import com.google.common.base.Preconditions;
import com.google.common.hash.Funnel;
import com.vehiclecontacting.config.BloomFilterConfig;
import com.vehiclecontacting.mapper.UserMapper;
import com.vehiclecontacting.pojo.User;
import io.jsonwebtoken.Claims;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component;
import java.util.*;
import java.util.concurrent.TimeUnit;
@Setter
@Getter
@Component
@Slf4j
public class RedisUtils {
@Autowired
private StringRedisTemplate redisTemplate;
@Autowired
private UserMapper userMapper;
//次数加1
public void addKeyByTime(String key,int hours){
//防止雪崩,加随机时间
String value = redisTemplate.opsForValue().get(key);
Random random = new Random();
long second = hours * 3600L + random.nextInt(100);
int cnt = 0;
if(value != null){
cnt = Integer.parseInt(value);
}
cnt ++;
//存入redis
redisTemplate.opsForValue().set(key,String.valueOf(cnt),second,TimeUnit.SECONDS);
}
//次数减1
public void subKeyByTime(String key,int hours){
//这里不会雪崩就不加随机时间了
String value = redisTemplate.opsForValue().get(key);
int cnt = 0;
if(value != null){
cnt = Integer.parseInt(value);
}
cnt --;
//存入redis
redisTemplate.opsForValue().set(key,String.valueOf(cnt),hours * 3600L,TimeUnit.SECONDS);
}
//存带有过期时间的key-value
public void saveByHoursTime(String key,String value,int hours){
//为防止缓存雪崩 加一个随机时间
Random random = new Random();
long second = hours * 3600L + random.nextInt(100);
redisTemplate.opsForValue().set(key,value,second,TimeUnit.SECONDS);
}
public void saveByMinutesTime(String key,String value,int minutes){
//为防止缓存雪崩 加一个随机时间
Random random = new Random();
long second = minutes * 60L + random.nextInt(25);
redisTemplate.opsForValue().set(key,value,second,TimeUnit.SECONDS);
}
//重置时间
public void resetExpire(String key,String value,int minutes){
//为防止缓存雪崩,加一个随机时间
Random random = new Random();
long seconds = minutes * 60L + random.nextInt(25);
redisTemplate.opsForValue().set(key,value,seconds,TimeUnit.SECONDS);
}
//判断key是否存在
public boolean hasKey(String key){
return redisTemplate.opsForValue().get(key) != null;
}
//删除key
public void delete(String key){
redisTemplate.delete(key);
}
//获取value
public String getValue(String key){
return redisTemplate.opsForValue().get(key);
}
//判断key是否在这个时间后
public boolean isAfterDate(String key,int minutes){
return redisTemplate.getExpire(key,TimeUnit.SECONDS) > (long) minutes * 60;
}
//从token中获取身份信息
public UsernamePasswordAuthenticationToken getAuthentication(String token){
//先解析token
Claims claims = JwtUtils.getTokenBody(token);
//获取用户名
String username = claims.getId();
//根据用户名判断是否为管理员,后面可根据
User user = userMapper.selectById(username);
Collection<GrantedAuthority> authList = new ArrayList<>();
authList.add(new SimpleGrantedAuthority("ROLE_USER"));
if(user == null){
log.error("用户不存在");
return null;
}
/*
if(user.getIsAdministrator() == 0){
//用户不是管理员
log.info("身份认证成功,用户:" + username + "是普通用户");
return new UsernamePasswordAuthenticationToken(new org.springframework.security.core.userdetails.User(username,user.getPassword(),authList),token,authList);
}else{
authList.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
}
log.info("身份认证成功,用户:" + username + "是管理员");
*/
return new UsernamePasswordAuthenticationToken(new org.springframework.security.core.userdetails.User(username,user.getPassword(),authList),token,authList);
}
public Map<Long,Integer> getAllScan(){
Map<Long,Integer> map = new HashMap<>();
Set<String> scanSet = redisTemplate.keys("scan_*");
if(scanSet != null){
//有需要更新的浏览量
for(String x:scanSet){
//获取次数
String value = redisTemplate.opsForValue().get(x);
if(value != null){
//存入map
map.put(Long.parseLong(x.substring(x.lastIndexOf("_") + 1)),Integer.parseInt(value));
}
}
}
log.info("需要增加浏览量的数据:" + map.toString());
return map;
}
public Map<Long,Integer> getAllLike(){
Map<Long,Integer> map = new HashMap<>();
Set<String> likeSet = redisTemplate.keys("cntLike_*");
if(likeSet != null){
//有点赞
for(String x:likeSet){
//获取次数
String value = redisTemplate.opsForValue().get(x);
if(value != null){
//存入map
map.put(Long.parseLong(x.substring(x.lastIndexOf("_") + 1)),Integer.parseInt(value));
}
}
}else{
log.info("8小时内暂时没有点赞信息");
}
log.info("8小时内点赞信息:" + map.toString());
return map;
}
public Map<Long,Integer> getAllFavor(){
Map<Long,Integer> map = new HashMap<>();
Set<String> favorSet = redisTemplate.keys("cntFavor_*");
if(favorSet != null){
//有新收藏
for(String x:favorSet){
//获取次数
String value = redisTemplate.opsForValue().get(x);
if(value != null){
//存入map
map.put(Long.parseLong(x.substring(x.lastIndexOf("_") + 1)),Integer.parseInt(value));
}
}
}else{
log.info("8小时内没有收藏信息");
}
log.info("8小时内收藏信息:" + map.toString());
return map;
}
public Map<String,Integer> getAllHotKeyword(){
Map<String,Integer> map = new HashMap<>();
Set<String> hotKeywordSet = redisTemplate.keys("hotKeyword_*");
if(hotKeywordSet != null){
//有新热词
for(String x:hotKeywordSet){
//获取次数
String value = redisTemplate.opsForValue().get(x);
if(value != null){
//存入map
map.put(x.substring(x.lastIndexOf("_") + 1),Integer.parseInt(value));
}
}
}else{
log.info("8小时内没有热词信息");
}
log.info("8小时内热词信息:" + map.toString());
return map;
}
/**
* 根据给定的布隆过滤器添加值
*/
public <T> void addByBloomFilter(BloomFilterConfig<T> bloomFilterHelper, String key, T value) {
Preconditions.checkArgument(bloomFilterHelper != null, "bloomFilterHelper不能为空");
int[] offset = bloomFilterHelper.murmurHashOffset(value);
for (int i : offset) {
System.out.println("key : " + key + " " + "value : " + i);
redisTemplate.opsForValue().setBit(key, i, true);
}
}
/**
* 根据给定的布隆过滤器判断值是否存在
*/
public <T> boolean includeByBloomFilter(BloomFilterConfig<T> bloomFilterHelper, String key, T value) {
Preconditions.checkArgument(bloomFilterHelper != null, "bloomFilterHelper不能为空");
int[] offset = bloomFilterHelper.murmurHashOffset(value);
for (int i : offset) {
System.out.println("key : " + key + " " + "value : " + i);
if (!redisTemplate.opsForValue().getBit(key, i)) {
return false;
}
}
return true;
}
@Bean
public BloomFilterConfig<String> initBloomFilterHelper() {
return new BloomFilterConfig<>((Funnel<String>) (from, into) -> into.putString(from, Charsets.UTF_8).putString(from, Charsets.UTF_8), 1000000, 0.01);
}
}
| 9,050 | 0.600143 | 0.593228 | 251 | 32.418327 | 29.467861 | 168 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.61753 | false | false | 13 |
958c9c725ee04eca0ac9c858fc9fdb83bc3dd4b3 | 2,534,030,763,720 | 5f95cdb31d3b73b73abcf5d7a7fccc68c556234c | /CursJavaPractic/Fitness/src/main/java/business/service/AccountService.java | 1f27924fdabfedab2ef067bae51858bf2e380170 | []
| no_license | CristianP88/CursJavaSDA | https://github.com/CristianP88/CursJavaSDA | 3e117b068450c51413c229e84c849d9ba714d9c1 | 14ee96fc116b1b5247d6b966c3c7a1ee9ccd7d89 | refs/heads/master | 2023-02-14T18:11:42.330000 | 2021-01-08T11:10:32 | 2021-01-08T11:10:32 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package business.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import persistence.dao.AccountDAO;
@Service
public class AccountService {
@Autowired
AccountDAO accountDAO;
public int deleteAccount(String userName) {
int result = accountDAO.deleteAccount(userName);
return result;
}
public int updateUserLogIn(boolean loggedIn,String userName){
int result = accountDAO.updateUserLogIn(loggedIn,userName);
return result;
}
public String cryptPassword(String password) {
Double crypt = (password.hashCode() + Math.sqrt(password.length()));
return String.valueOf(crypt);
}
public String cryptPass(String password) {
char[] chars = password.toCharArray();
String newPassword = " ";
for (char c : chars) {
c += 3;
newPassword += c;
}
return newPassword;
}
public String checkRegistration(String userName, String password) {
String retrievedPassword = accountDAO.checkRegistration(userName, password);
return retrievedPassword;
}
public long countUserName(String userName) {
long result = accountDAO.countUserName(userName);
return result;
}
public int changeUsername(String newUsername, String userName) {
int result = accountDAO.changeUserName(newUsername, userName);
return result;
}
}
| UTF-8 | Java | 1,492 | java | AccountService.java | Java | []
| null | []
| package business.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import persistence.dao.AccountDAO;
@Service
public class AccountService {
@Autowired
AccountDAO accountDAO;
public int deleteAccount(String userName) {
int result = accountDAO.deleteAccount(userName);
return result;
}
public int updateUserLogIn(boolean loggedIn,String userName){
int result = accountDAO.updateUserLogIn(loggedIn,userName);
return result;
}
public String cryptPassword(String password) {
Double crypt = (password.hashCode() + Math.sqrt(password.length()));
return String.valueOf(crypt);
}
public String cryptPass(String password) {
char[] chars = password.toCharArray();
String newPassword = " ";
for (char c : chars) {
c += 3;
newPassword += c;
}
return newPassword;
}
public String checkRegistration(String userName, String password) {
String retrievedPassword = accountDAO.checkRegistration(userName, password);
return retrievedPassword;
}
public long countUserName(String userName) {
long result = accountDAO.countUserName(userName);
return result;
}
public int changeUsername(String newUsername, String userName) {
int result = accountDAO.changeUserName(newUsername, userName);
return result;
}
}
| 1,492 | 0.671582 | 0.670912 | 56 | 25.642857 | 25.002449 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 13 |
38d2029d0b286e1b35c54deded0658acb4e868ce | 2,534,030,762,007 | e0449a1669b3b4e6a794829a945c2ad52767f2a2 | /src/main/java/shiro/Test.java | 0e2748dd6995c76dd0e7bc8b68e7800ad689c4a4 | []
| no_license | wusiyue/testjava2 | https://github.com/wusiyue/testjava2 | ac8977b61db31e9c239aa7334a35c58eeb11ff58 | 50b6ee6fc30ad5c66d92dd355eb070ed139dbea5 | refs/heads/master | 2018-09-19T01:27:45.081000 | 2018-09-07T09:55:16 | 2018-09-07T09:55:16 | 127,684,774 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package shiro;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.util.Factory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.shiro.mgt.SecurityManager;
import java.io.IOException;
/**
* 我是干什么的
*
* @author wusiyue
* @create 2018-03-30 11:38
**/
public class Test {
private static final Logger log = LoggerFactory.getLogger(Test.class);
public static void main(String[] args) throws InterruptedException {
log.info("My First Apache Shiro Application");
Factory<SecurityManager> factory=new IniSecurityManagerFactory("classpath:shiro.ini");//shiro就相当于realm了
SecurityManager securityManager=factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);
Thread t=new Thread(new Task());
t.run();
try {
String s;
do {
System.out.println("请输入字符串:yes:再次以当前线程访问、no换一个线程、stop停止");
//数组来缓冲
byte[] b = new byte[512];
//读取数据
int n = System.in.read(b);
//转换为字符串
s = new String(b, 0, n);
log.info("输入的字符串为:" + s.substring(0,s.indexOf('\n')));
if ((s.indexOf("yes")> -1)) {
t.run();
} else if ((s.indexOf("no")> -1)) {
new Thread(new Task()).start();
Thread.sleep(1000);
}
else if((s.indexOf("stop")> -1)){
break;
}
else {
log.info("你输入的啥,我啥都不做");
}
}while (true);
} catch (IOException e) {
e.printStackTrace();
}
}
}
| UTF-8 | Java | 1,943 | java | Test.java | Java | [
{
"context": "java.io.IOException;\n\n\n/**\n * 我是干什么的\n *\n * @author wusiyue\n * @create 2018-03-30 11:38\n **/\n\npublic class Te",
"end": 319,
"score": 0.9995817542076111,
"start": 312,
"tag": "USERNAME",
"value": "wusiyue"
}
]
| null | []
| package shiro;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.util.Factory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.shiro.mgt.SecurityManager;
import java.io.IOException;
/**
* 我是干什么的
*
* @author wusiyue
* @create 2018-03-30 11:38
**/
public class Test {
private static final Logger log = LoggerFactory.getLogger(Test.class);
public static void main(String[] args) throws InterruptedException {
log.info("My First Apache Shiro Application");
Factory<SecurityManager> factory=new IniSecurityManagerFactory("classpath:shiro.ini");//shiro就相当于realm了
SecurityManager securityManager=factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);
Thread t=new Thread(new Task());
t.run();
try {
String s;
do {
System.out.println("请输入字符串:yes:再次以当前线程访问、no换一个线程、stop停止");
//数组来缓冲
byte[] b = new byte[512];
//读取数据
int n = System.in.read(b);
//转换为字符串
s = new String(b, 0, n);
log.info("输入的字符串为:" + s.substring(0,s.indexOf('\n')));
if ((s.indexOf("yes")> -1)) {
t.run();
} else if ((s.indexOf("no")> -1)) {
new Thread(new Task()).start();
Thread.sleep(1000);
}
else if((s.indexOf("stop")> -1)){
break;
}
else {
log.info("你输入的啥,我啥都不做");
}
}while (true);
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 1,943 | 0.530748 | 0.516343 | 65 | 26.76923 | 23.91766 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.476923 | false | false | 13 |
bd7bc4209e0ca738f82918c0f2ddc1ce61566f2b | 11,166,915,009,003 | ca9c3d3c69626d184cd64af8d4533a22590dad2c | /test/com/rtg/reader/FormatCliTest.java | 9f1d7945050c1557db5ea5e0635e2cc03181a4bc | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
]
| permissive | thoughtsynapse/rtg-tools | https://github.com/thoughtsynapse/rtg-tools | 0c0e1360cd02c88bdd63ef5f669eb01b134cba4b | 32d4c2d2d340cb0288f68ddd008d29564bcfef13 | refs/heads/master | 2023-04-28T18:58:41.630000 | 2021-05-18T01:54:10 | 2021-05-20T01:20:07 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Copyright (c) 2014. Real Time Genomics Limited.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.rtg.reader;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import com.rtg.launcher.AbstractCli;
import com.rtg.launcher.AbstractCliTest;
import com.rtg.launcher.MainResult;
import com.rtg.mode.DNAFastaSymbolTable;
import com.rtg.reader.FormatCli.BadFormatCombinationException;
import com.rtg.reader.FormatCli.PrereadExecutor;
import com.rtg.reader.FormatCli.PrereadExecutor.SequenceProcessor;
import com.rtg.util.Constants;
import com.rtg.util.License;
import com.rtg.util.StringUtils;
import com.rtg.util.TestUtils;
import com.rtg.util.cli.CFlags;
import com.rtg.util.diagnostic.Diagnostic;
import com.rtg.util.diagnostic.NoTalkbackSlimException;
import com.rtg.util.intervals.LongRange;
import com.rtg.util.io.FileUtils;
import com.rtg.util.io.MemoryPrintStream;
import com.rtg.util.io.TestDirectory;
import com.rtg.util.test.FileHelper;
/**
* Test class for corresponding class.
*/
public class FormatCliTest extends AbstractCliTest {
@Override
protected AbstractCli getCli() {
return new FormatCli();
}
public void testHelp() {
checkHelp("rtg format"
, "Converts the contents of sequence data files (FASTA/FASTQ/SAM/BAM) into the RTG Sequence Data File (SDF) format."
, "-f,", "--format=FORMAT", "format of input. Allowed values are [fasta, fastq"
, "-q", "--quality-format=FORMAT", "quality data encoding", "Allowed values are [sanger, solexa, illumina] (Default is sanger)"
, "--input-list-file=FILE", "file containing a list of input read files (1 per line)"
, "-l,", "--left=FILE", "left input file for FASTA/FASTQ paired end data"
, "-o,", "--output=SDF", "name of output SDF"
, "-p,", "--protein", "input is protein. If this option is not specified, then the input is assumed to consist of nucleotides"
, "-r,", "--right=FILE", "right input file for FASTA/FASTQ paired end data"
, "FILE+", "input sequence files. May be specified 0 or more times"
, "--duster", "treat lower case residues as unknowns"
, "--exclude=STRING", "exclude input sequences based on their name. If the input sequence contains the specified string then that sequence is excluded from the SDF. May be specified 0 or more times"
, "--no-names", "do not include name data in the SDF output"
, "--no-quality", "do not include quality data in the SDF output"
, "--allow-duplicate-names"
, "--sam-rg"
, "--select-read-group"
);
checkExtendedHelp("rtg format"
, "--Xcompress=BOOL", "compress sdf (Default is " + true + ")"
);
}
public void testCFlagsQ() throws Exception {
Diagnostic.setLogStream();
final File dir = FileUtils.createTempDir("formattest", "badfiles");
try {
final File xx = new File(dir, "xx");
FileUtils.stringToFile("", xx);
final File nsd = new File(dir, "no-such-dir");
checkHandleFlagsOut("-p", "-o", nsd.getPath(), "-f", "fastq", "-q", "sanger", xx.getPath());
final CFlags flags = getCFlags();
assertTrue(flags.isSet("protein"));
assertEquals("fastq", flags.getValue("format"));
assertEquals(nsd.getPath(), ((File) flags.getValue("output")).getPath());
assertEquals(xx, flags.getAnonymousFlag(0).getValue());
} finally {
assertTrue(FileHelper.deleteAll(dir));
}
}
private static final String JUNITOUT = ".junitout";
private static final String EXPECTED_MSG = "" + StringUtils.LS
+ "Format : FASTA" + StringUtils.LS
+ "Type : DNA" + StringUtils.LS
+ "Number of sequences: 2" + StringUtils.LS
+ "Total residues : 10" + StringUtils.LS
+ "Minimum length : 5" + StringUtils.LS
+ "Mean length : 5" + StringUtils.LS
+ "Maximum length : 5" + StringUtils.LS;
public void testValidUseA() throws Exception {
try (final TestDirectory tempDir = new TestDirectory("format")) {
final File raw = new File(tempDir, "test");
final File outputDir = new File(tempDir, JUNITOUT);
FileUtils.stringToFile(">x\naCTGN\n>y\nACTGN\n", raw);
testValidUse(new String[] {"-o", outputDir.getPath(), raw.getPath(), "--duster", "--exclude", "y"}, outputDir);
}
}
public void testValidUseAList() throws Exception {
try (final TestDirectory tempDir = new TestDirectory("format")) {
final File raw = new File(tempDir, "test");
final File outputDir = new File(tempDir, JUNITOUT);
FileUtils.stringToFile(">x\naCTGN\n>y\nACTGN\n", raw);
final File list = new File(tempDir, "list");
FileUtils.stringToFile(raw.getPath(), list);
testValidUse(new String[]{"-o", outputDir.getPath(), "-I", list.getPath(), "--duster", "--exclude", "y"}, outputDir);
}
}
private void testValidUse(String[] args, File outputDir) throws IOException {
try (final TestDirectory tempDir = new TestDirectory("format")) {
final String outStr = checkMainInitOk(args);
TestUtils.containsAll(outStr, EXPECTED_MSG
, "Formatting FASTA data"
, "Input Data"
, "Files : "
, StringUtils.LS + StringUtils.LS + "Output Data"
, "SDF-ID : "
, "Number of sequences: 1" + StringUtils.LS
+ "Total residues : 5" + StringUtils.LS
+ "Minimum length : 5" + StringUtils.LS
+ "Mean length : 5" + StringUtils.LS
+ "Maximum length : 5" + StringUtils.LS
+ StringUtils.LS
+ "There were 1 sequences skipped due to filters" + StringUtils.LS
+ "There were 1 residues converted from lower case to unknowns");
assertTrue(outputDir.isDirectory());
assertTrue(new File(outputDir, "mainIndex").exists());
final File summary = new File(outputDir, "summary.txt");
assertTrue(summary.exists());
final String sum = FileUtils.fileToString(summary);
assertTrue(sum, sum.contains(EXPECTED_MSG));
final File progress = new File(outputDir, "progress");
assertTrue(progress.exists());
final String prog = FileUtils.fileToString(progress);
TestUtils.containsAll(prog, "Formatting FASTA data");
final File outf = new File(tempDir, "out.fasta");
MainResult.run(new Sdf2Fasta(), "-o", outf.getPath(), "-i", outputDir.getPath(), "-Z");
assertTrue(outf.exists());
assertFalse(outf.isDirectory());
try (BufferedReader r = new BufferedReader(new FileReader(outf))) {
assertEquals(">x", r.readLine());
assertEquals("NCTGN", r.readLine());
assertNull(r.readLine());
}
}
}
public void testDuplicateError() throws Exception {
Diagnostic.setLogStream();
try (final TestDirectory tempDir = new TestDirectory("format")) {
final File inputA = new File(tempDir, "inputA.fasta");
final File inputB = new File(tempDir, "inputB.fasta");
FileUtils.stringToFile(">x\nactgn" + StringUtils.LS, inputA);
FileUtils.stringToFile(">y\nactgn" + StringUtils.LS + ">x\nactgn" + StringUtils.LS, inputB);
final File outputDir = new File(tempDir, "output");
final File dupFile = new File(outputDir.getAbsolutePath(), "duplicate-names.txt");
final String err = checkMainInitWarn("-o", outputDir.getAbsolutePath(), inputA.getAbsolutePath(), inputB.getAbsolutePath());
assertTrue(outputDir.exists());
assertTrue(dupFile.exists());
assertTrue(err.contains("Duplicate Sequence Names in Input"));
assertEquals("x" + StringUtils.LS, FileUtils.fileToString(dupFile));
}
}
public void testValidUseQ() throws Exception {
try (final TestDirectory tempDir = new TestDirectory("format")) {
final File raw = new File(tempDir, "raw");
FileUtils.stringToFile("@x\n" + "actgn\n" + "+x\n" + "ACTGN\n", raw);
final File outputDir = new File(tempDir, JUNITOUT);
final String bout = checkMainInitOk("-o", outputDir.getPath(), "-f", "fastq", "-q", "sanger", raw.getPath());
mNano.check("format-useq.txt", StringUtils.grepMinusV(bout, "SDF-ID|Processing|Formatting FASTQ"));
assertTrue(outputDir.isDirectory());
assertTrue(new File(outputDir, "mainIndex").exists());
final File summary = new File(outputDir, "summary.txt");
assertTrue(summary.exists());
final String sum = FileUtils.fileToString(summary);
mNano.check("format-useq.txt", StringUtils.grepMinusV(sum, "SDF-ID"));
final File outf = new File(tempDir, "out.fasta");
//System.err.println("bos 1 ' " + bos.toString());
MainResult res = MainResult.run(new SdfStatistics(), outputDir.getAbsolutePath());
assertEquals(res.err(), 0, res.rc());
assertTrue(res.out().contains("Sequence names : yes"));
assertTrue(res.out().contains("Residue qualities : yes"));
res = MainResult.run(new Sdf2Fasta(), "-o", outf.getPath(), "-i", outputDir.getPath(), "-Z");
assertEquals(res.err(), 0, res.rc());
assertEquals(0, res.out().length());
assertTrue(outf.exists());
assertFalse(outf.isDirectory());
try (BufferedReader r = new BufferedReader(new FileReader(outf))) {
assertEquals(">x", r.readLine());
assertEquals("ACTGN", r.readLine());
assertNull(r.readLine());
}
}
}
public void testNoNames() throws Exception {
try (final TestDirectory tempDir = new TestDirectory("format")) {
final File raw = new File(tempDir, "raw");
FileUtils.stringToFile("@x\n" + "actgn\n" + "+x\n" + "ACTGN\n", raw);
final File outputDir = new File(tempDir, JUNITOUT);
checkMainInitOk("-o", outputDir.getPath(), "-f", "fastq", "-q", "sanger", raw.getPath(), "--no-names");
final MainResult res = MainResult.run(new SdfStatistics(), outputDir.getAbsolutePath());
assertEquals(res.err(), 0, res.rc());
assertTrue(res.out(), res.out().contains("Sequence names : no"));
}
}
public void testNoQuality() throws Exception {
try (final TestDirectory tempDir = new TestDirectory("format")) {
final File raw = new File(tempDir, "raw");
FileUtils.stringToFile("@x\n" + "actgn\n" + "+x\n" + "ACTGN\n", raw);
final File outputDir = new File(tempDir, JUNITOUT);
checkMainInitOk("-o", outputDir.getPath(), "-f", "fastq", "-q", "sanger", raw.getPath(), "--no-quality");
final MainResult res = MainResult.run(new SdfStatistics(), outputDir.getAbsolutePath());
assertEquals(res.err(), 0, res.rc());
assertTrue(res.out(), res.out().contains("Residue qualities : no"));
}
}
public void testValidUsePaired() throws Exception {
try (final TestDirectory tempDir = new TestDirectory("format")) {
final File raw1 = new File(tempDir, "raw1");
final File raw2 = new File(tempDir, "raw2");
FileUtils.stringToFile(">x\n" + "aCTGN\n>y\nACTGN\n", raw1);
FileUtils.stringToFile(">x\n" + "ACTGN\n>y\nACTGN\n", raw2);
final File outputDir = new File(tempDir, JUNITOUT);
final MainResult res = runFormat(outputDir, "@RG\tID:id\tSM:sm\tPL:ILLUMINA",
"-o", outputDir.getPath(), "-f", "fasta", "-l" , raw1.getPath(), "-r", raw2.getPath(), "--duster", "--exclude", "y", "--sam-rg", "@RG\\tID:id\\tSM:sm\\tPL:ILLUMINA");
TestUtils.containsAll(res.out()
, "Formatting paired-end FASTA data"
, "Input Data" + StringUtils.LS
+ "Files : raw1 raw2" + StringUtils.LS
+ "Format : paired-end FASTA" + StringUtils.LS
+ "Type : DNA" + StringUtils.LS
+ "Number of pairs : 2" + StringUtils.LS
+ "Number of sequences: 4" + StringUtils.LS
+ "Total residues : 20" + StringUtils.LS
+ "Minimum length : 5" + StringUtils.LS
+ "Mean length : 5" + StringUtils.LS
+ "Maximum length : 5" + StringUtils.LS
+ StringUtils.LS
+ "Output Data" + StringUtils.LS
+ "SDF-ID : "
, "Number of pairs : 1" + StringUtils.LS
+ "Number of sequences: 2" + StringUtils.LS
+ "Total residues : 10" + StringUtils.LS
+ "Minimum length : 5" + StringUtils.LS
+ "Mean length : 5" + StringUtils.LS
+ "Maximum length : 5" + StringUtils.LS
+ StringUtils.LS
+ "There were 1 pairs skipped due to filters" + StringUtils.LS
+ "There were 1 residues converted from lower case to unknowns" + StringUtils.LS
);
assertTrue(outputDir.isDirectory());
assertTrue(new File(outputDir, "left").isDirectory());
assertTrue(new File(outputDir, "right").isDirectory());
assertTrue(new File(new File(outputDir, "left"), "mainIndex").exists());
assertTrue(new File(new File(outputDir, "right"), "mainIndex").exists());
final File progress = new File(outputDir, "progress");
assertTrue(progress.exists());
final String prog = FileUtils.fileToString(progress);
TestUtils.containsAll(prog, "Formatting paired-end FASTA data", "paired-end SDF");
}
}
public void testUnevenPaired() throws Exception {
try (final TestDirectory tempDir = new TestDirectory("format")) {
final File rawLeft = new File(tempDir, "left.fasta");
final File rawRight = new File(tempDir, "right.fasta");
FileUtils.stringToFile("@x\n" + "actgn\n" + "+x\n" + "ACTGN\n@x2\n" + "actgn\n" + "+x2\n" + "ACTGN\n", rawLeft);
FileUtils.stringToFile("@x\n" + "actgn\n" + "+x\n" + "ACTGN\n", rawRight);
final MemoryPrintStream out = new MemoryPrintStream();
final MemoryPrintStream err = new MemoryPrintStream();
final File outputDir = new File(tempDir, JUNITOUT);
final String s = checkMainInitBadFlags("-o", outputDir.getPath(), "-f", "fastq", "-q", "sanger", "-l", rawLeft.getPath(), "-r", rawRight.getPath());
assertTrue(outputDir.isDirectory());
assertTrue(new File(outputDir, "left").isDirectory());
assertTrue(new File(outputDir, "right").isDirectory());
assertTrue(new File(new File(outputDir, "left"), "mainIndex").exists());
assertTrue(new File(new File(outputDir, "right"), "mainIndex").exists());
assertTrue(s, s.contains("Invalid input, paired end data must have same number of sequences. Left had: 2 Right had: 1"));
out.close();
err.close();
}
}
public void testValidUseCG() throws Exception {
if (License.isDeveloper()) {
try (final TestDirectory tempDir = new TestDirectory("format")) {
final File raw1 = new File(tempDir, "raw1.fq");
final File raw2 = new File(tempDir, "raw2.fq");
FileUtils.stringToFile("@x\n" + "actgn\n" + "+x\n" + "ACTGN\n", raw1);
FileUtils.stringToFile("@x\n" + "actgn\n" + "+x\n" + "ACTGN\n", raw2);
final File outputDir = new File(tempDir, JUNITOUT);
final String out = checkMainInitOk("-o", outputDir.getPath(), "-f", "fastq-cg", "-l", raw1.getPath(), "-r", raw2.getPath());
assertTrue(out.contains("Format : paired-end FASTQ-CG"));
assertTrue(out.contains("Type : DNA"));
assertTrue(out.contains("SDF-ID"));
assertTrue(out.contains("Number of sequences: 2"));
assertTrue(out.contains("Total residues : 10"));
assertTrue(out.contains("Minimum length : 5"));
assertTrue(out.contains("Maximum length : 5"));
assertTrue(outputDir.isDirectory());
assertTrue(new File(outputDir, "left").isDirectory());
assertTrue(new File(outputDir, "right").isDirectory());
assertTrue(new File(new File(outputDir, "left"), "mainIndex").exists());
assertTrue(new File(new File(outputDir, "right"), "mainIndex").exists());
}
}
}
public void testValidUseProtein() throws Exception {
try (TestDirectory tempDir = new TestDirectory("format")) {
final File raw = new File(tempDir, "in.fasta");
FileUtils.stringToFile(">x\nX*ARNDCQEGHILKMFPSTWYV\n", raw);
final File outputDir = new File(tempDir, JUNITOUT);
final String outStr = checkMainInitOk("-o", outputDir.getPath(), "-p", raw.getPath());
mNano.check("format-useprotein.txt", StringUtils.grepMinusV(outStr, "SDF-ID|Processing|Formatting FASTA"));
assertTrue(outputDir.isDirectory());
assertTrue(new File(outputDir, "mainIndex").exists());
final File summary = new File(outputDir, "summary.txt");
assertTrue(summary.exists());
final String sum = FileUtils.fileToString(summary);
mNano.check("format-useprotein.txt", StringUtils.grepMinusV(sum, "SDF-ID"));
final File outf = new File(tempDir, "out.fasta");
final MainResult res = MainResult.run(new Sdf2Fasta(), "-o", outf.getPath(), "-i", outputDir.getPath(), "-Z");
assertEquals(0, res.out().length());
assertTrue(outf.exists());
assertFalse(outf.isDirectory());
try (BufferedReader r = new BufferedReader(new FileReader(outf))) {
assertEquals(">x", r.readLine());
assertEquals("X*ARNDCQEGHILKMFPSTWYV", r.readLine());
assertNull(r.readLine());
}
}
}
public void testBadUse() {
final String e = checkMainInitBadFlags("--no-such-option");
assertTrue(e.contains("Error: Unknown flag --no-such-option"));
}
private static final String EXPECTED_ERROR2 = "Error: File not found: \"" + File.separator + "in_a_small_hole_lived_a_hobbit\"" + StringUtils.LS
+ "Error: There were 1 invalid input file paths" + StringUtils.LS;
public void testBadFiles() throws Exception {
try (TestDirectory dir = new TestDirectory("format")) {
final File out = new File(dir, "prereadertestshouldnthappen");
final String e = checkMainInitBadFlags("-o", out.getPath(), File.separator + "in_a_small_hole_lived_a_hobbit");
assertEquals(e, EXPECTED_ERROR2, e);
}
}
public void testInputTestingFlags() throws IOException {
Diagnostic.setLogStream();
try (TestDirectory dir = new TestDirectory("format")) {
final File input = new File(dir, "in");
FileUtils.stringToFile("", input);
final File outDir = new File(dir, "out");
TestUtils.containsAllUnwrapped(checkHandleFlagsErr("-o", outDir.getPath()), "No input files specified.");
TestUtils.containsAllUnwrapped(checkHandleFlagsErr("-o", outDir.getPath(), "-l", input.getPath()), "Both left and right reads must be specified.");
TestUtils.containsAllUnwrapped(checkHandleFlagsErr("-o", outDir.getPath(), "-r", input.getPath()), "Both left and right reads must be specified.");
TestUtils.containsAllUnwrapped(checkHandleFlagsErr("-o", outDir.getPath(), "-l", input.getPath(), "-r", input.getPath(), "-p"), "Cannot set protein flag when left and right files are specified.");
TestUtils.containsAllUnwrapped(checkHandleFlagsErr("-o", outDir.getPath(), "-l", input.getPath(), input.getPath()), "Either specify individual input files or left and right files, not both.");
TestUtils.containsAllUnwrapped(checkHandleFlagsErr("-o", outDir.getPath(), "-r", input.getPath(), input.getPath()), "Either specify individual input files or left and right files, not both.");
}
}
public void testFormatflag() throws IOException {
Diagnostic.setLogStream();
try (TestDirectory que = new TestDirectory("format")) {
final File f = new File(que, "in");
FileUtils.stringToFile("", f);
final String[] args = {
"-o", "res",
f.getPath(),
"-f", "embl"
};
final String err = checkHandleFlagsErr(args);
assertTrue(err, err.contains("Invalid value \"embl\" for flag -f"));
}
}
public void testOutputflag() throws IOException {
Diagnostic.setLogStream();
final File que = FileUtils.createTempDir("format", "pre");
final File i = new File(que, "test");
assertTrue(i.createNewFile());
final String[] args = {
"-o", que.getPath(),
i.getPath(),
};
final String result = checkHandleFlagsErr(args);
TestUtils.containsAllUnwrapped(result, "The directory \"" + que.getPath() + "\" already exists. Please remove it first or choose a different directory.");
FileHelper.deleteAll(que);
}
public void testOutputAsFileflag() throws IOException {
Diagnostic.setLogStream();
try (TestDirectory dir = new TestDirectory("format")) {
final File que = new File(dir, "query");
FileUtils.stringToFile("", que);
final String[] args = {
"-o", que.getPath(),
que.getPath(),
};
final String result = checkHandleFlagsErr(args);
TestUtils.containsAllUnwrapped(result, "The directory \"" + que.getPath() + "\" already exists. Please remove it first or choose a different directory.");
}
}
public void testSolexa13Format() throws Exception {
try (TestDirectory tempDir = new TestDirectory("format")) {
final File outputDir = new File(tempDir, JUNITOUT);
final File input = new File(tempDir, "in");
FileUtils.stringToFile("^", input);
String err = checkMainInitBadFlags("-o", outputDir.getPath(), "-f", "fastq", "-q", "solexa1.2", input.getPath());
assertTrue("error was: " + err, err.contains("Invalid value \"solexa1.2\" for flag -q."));
err = checkMainInitBadFlags("-o", outputDir.getPath(), "-f", "fastq", "-q", "illumina", input.getPath());
assertTrue("error was: " + err, err.contains("Unrecognized symbols appeared before label symbol. Last sequence read was: \"<none>\""));
}
}
public void testErrorHandling() throws IOException {
try (final TestDirectory tempDir = new TestDirectory("format")) {
final File outputDir = new File(tempDir, JUNITOUT);
final File raw = new File(tempDir, "test");
FileUtils.stringToFile(">x\nX*ARNDCQEGHILKMFPSTWYV\n", raw);
String err = checkMainInitBadFlags("-o", outputDir.getPath(), "-f", "fastq", "-q", "sanger", "-p", raw.getPath());
TestUtils.containsAll(err, "Incompatible sequence type and file format. format=FASTQ protein=" + true);
final File outputDir2 = new File(tempDir, "blah");
err = checkMainInitBadFlags("-o", outputDir2.getPath(), "-f", "fasta", "--trim-threshold", "15", "-p", raw.getPath());
TestUtils.containsAll(err, "Input must contain qualities to perform quality-based read trimming.");
}
}
public void testGetFormat() {
assertEquals(SourceFormat.FASTA, FormatCli.getFormat("fasta", null, true, false).getSourceFormat());
assertEquals(SourceFormat.FASTQ, FormatCli.getFormat("fastq", "sanger", true, false).getSourceFormat());
assertEquals(QualityFormat.SOLEXA, FormatCli.getFormat("fastq", "solexa", true, false).getQualityFormat());
assertEquals(QualityFormat.SOLEXA1_3, FormatCli.getFormat("fastq", "illumina", true, false).getQualityFormat());
try {
FormatCli.getFormat("blah", null, true, false);
} catch (final NoTalkbackSlimException e) {
assertEquals("Invalid file format=blah", e.getMessage());
}
}
public void testSequenceProcessor() throws IOException {
final File dir = FileUtils.createTempDir("test", "number");
try {
final List<InputStream> list = new ArrayList<>();
final SequenceProcessor p = new SequenceProcessor(new FastaSequenceDataSource(list, new DNAFastaSymbolTable()), PrereadType.UNKNOWN, PrereadArm.UNKNOWN, dir, null, null, false, null);
assertEquals(Constants.MAX_FILE_SIZE, p.mWriter.getSizeLimit());
} finally {
FileHelper.deleteAll(dir);
}
}
private static final DataSourceDescription FASTQ_DS = new DataSourceDescription(SourceFormat.FASTQ, QualityFormat.SANGER, false, false, false);
public void testBadFormatCombinationException() throws IOException {
Diagnostic.setLogStream();
final PrereadExecutor ex = new PrereadExecutor(true, false, FASTQ_DS, null, null, null, false, false, false, true, null, null, false);
try {
ex.performPreread(null);
fail();
} catch (final BadFormatCombinationException e) {
assertEquals("Incompatible sequence type and file format. format=FASTQ protein=" + true, e.getMessage());
}
}
public void testFormattingMessage() {
testMessage("FASTQ-CG", new DataSourceDescription(SourceFormat.FASTQ, QualityFormat.UNKNOWN, true, false, true));
testMessage("FASTA", new DataSourceDescription(SourceFormat.FASTA, QualityFormat.UNKNOWN, false, false, false));
testMessage("FASTQ", FASTQ_DS);
testMessage("FASTQ-SOLEXA", new DataSourceDescription(SourceFormat.FASTQ, QualityFormat.SOLEXA, false, false, false));
testMessage("FASTQ-SOLEXA1_3", new DataSourceDescription(SourceFormat.FASTQ, QualityFormat.SOLEXA1_3, false, false, false));
testMessage("SAM/BAM", new DataSourceDescription(SourceFormat.SAM, QualityFormat.SANGER, true, false, false));
testMessage("SAM/BAM", new DataSourceDescription(SourceFormat.SAM, QualityFormat.SANGER, false, false, false));
}
private void testMessage(String formatString, DataSourceDescription desc) {
if (desc.isPairedEnd()) {
assertEquals("Formatting paired-end " + formatString + " data", FormatCli.PrereadExecutor.formattingMessage(desc));
} else {
assertEquals("Formatting " + formatString + " data", FormatCli.PrereadExecutor.formattingMessage(desc));
}
}
public void testSamRGFormat() throws IOException {
try (TestDirectory dir = new TestDirectory()) {
final File input = new File(dir, "input.sam");
final File output = new File(dir, "output");
FileHelper.resourceToFile("com/rtg/sam/resources/mated.sam", input);
runFormat(output, "@RG\tID:rg1\tSM:sm1\tPL:ILLUMINA",
input.getPath(), "-o", output.getPath(), "-f", "sam-pe");
}
}
public void testSamRGFormatCustom() throws IOException {
try (TestDirectory dir = new TestDirectory()) {
final File input = new File(dir, "input.sam");
final File output = new File(dir, "output");
final String custom = "@RG\tID:rg999\tPL:NOT_ILLUMINA\tSM:sample".replaceAll("\t", "\\\\t");
FileHelper.resourceToFile("com/rtg/sam/resources/mated.sam", input);
runFormat(output, "@RG\tID:rg999\tPL:NOT_ILLUMINA\tSM:sample",
input.getPath(), "-o", output.getPath(), "-f", "sam-pe", "--sam-rg", custom);
}
}
private MainResult runFormat(File output, String expected, String... args) throws IOException {
final MainResult res = checkMainInit(args);
final DefaultSequencesReader leftReader = new DefaultSequencesReader(new File(output, "left"), LongRange.NONE);
assertEquals(expected, leftReader.samReadGroup());
final DefaultSequencesReader rightReader = new DefaultSequencesReader(new File(output, "right"), LongRange.NONE);
assertEquals(expected, rightReader.samReadGroup());
return res;
}
public void testSamRGFormatMultiple() throws IOException {
try (TestDirectory dir = new TestDirectory()) {
final File input = new File(dir, "input.sam");
final File output = new File(dir, "output");
FileHelper.resourceToFile("com/rtg/reader/resources/mated.sam", input);
runFormat(output, "@RG\tID:rg2\tSM:doggy\tPL:Sturdy",
input.getPath(), "-o", output.getPath(), "-f", "sam-pe", "--select-read-group", "rg2");
}
}
public void testDedupSecondary() throws IOException {
try (TestDirectory dir = new TestDirectory()) {
final File input = new File(dir, "input.sam");
final File output = new File(dir, "output");
FileHelper.resourceToFile("com/rtg/reader/resources/mated.sam", input);
final String err = checkMainInitWarn(input.getPath(), "-o", output.getPath(), "-f", "sam-pe", "--select-read-group", "rg1", "--Xdedup-secondary-alignments");
TestUtils.containsAll(err, "1 reads missing a pair");
try (final DefaultSequencesReader rightReader = new DefaultSequencesReader(new File(output, "right"), LongRange.NONE)) {
assertEquals(2, rightReader.numberSequences());
final StringBuilder sb = new StringBuilder();
final SequencesIterator it = rightReader.iterator();
while (it.nextSequence()) {
sb.append(it.currentName());
}
TestUtils.containsAll(sb.toString(), "48218590", "48851323");
}
}
}
public void testHandleDupAndSupplemental() throws IOException {
try (TestDirectory dir = new TestDirectory()) {
final File input = new File(dir, "input.sam");
final File output = new File(dir, "output");
FileHelper.resourceToFile("com/rtg/reader/resources/mated-dups.sam", input);
final String err = checkMainInitWarn(input.getPath(), "-o", output.getPath(), "-f", "sam-pe", "--select-read-group", "rg1", "--Xdedup-secondary-alignments");
TestUtils.containsAll(err, "Read 48851323 is duplicated in SAM input", "1 reads missing a pair", "1 records ignored as duplicates in input");
try (final DefaultSequencesReader rightReader = new DefaultSequencesReader(new File(output, "right"), LongRange.NONE)) {
assertEquals(2, rightReader.numberSequences());
final StringBuilder sb = new StringBuilder();
final SequencesIterator it = rightReader.iterator();
while (it.nextSequence()) {
sb.append(it.currentName());
}
TestUtils.containsAll(sb.toString(), "48218590", "48851323");
}
}
}
public void testUnmatchableReadGroup() throws IOException {
try (TestDirectory dir = new TestDirectory()) {
final File input = new File(dir, "input.sam");
final File output = new File(dir, "output");
FileHelper.resourceToFile("com/rtg/reader/resources/mated.sam", input);
final String err = checkMainInitBadFlags(input.getPath(), "-o", output.getPath(), "-f", "sam-pe", "--select-read-group", "I am not here");
TestUtils.containsAll(err, "No read group information matching \"I am not here\" present in the input file");
}
}
public void testMultifile() throws IOException {
try (TestDirectory dir = new TestDirectory()) {
final File input = new File(dir, "input.sam");
final File input2 = new File(dir, "input2.sam");
final File output = new File(dir, "output");
FileHelper.resourceToFile("com/rtg/reader/resources/mated.sam", input);
FileHelper.resourceToFile("com/rtg/sam/resources/mated.sam", input2);
runFormat(output, "@RG\tID:rg1\tSM:sm1\tPL:ILLUMINA",
input.getPath(), input2.getPath(), "-o", output.getPath(), "-f", "sam-pe", "--select-read-group", "rg1");
}
}
public void testMultifileMissingFromSecond() throws IOException {
try (TestDirectory dir = new TestDirectory()) {
final File input = new File(dir, "input.sam");
final File input2 = new File(dir, "input2.sam");
final File output = new File(dir, "output");
FileHelper.resourceToFile("com/rtg/reader/resources/mated.sam", input);
FileHelper.resourceToFile("com/rtg/sam/resources/mated.sam", input2);
final String err = checkMainInitBadFlags(input2.getPath(), input.getPath(), "-o", output.getPath(), "-f", "sam-pe", "--select-read-group", "rg2");
TestUtils.containsAll(err, "No read group information matching \"rg2\" present in the input file ");
}
}
public void testSamRGFormatMultipleFail() throws IOException {
try (TestDirectory dir = new TestDirectory()) {
final File input = new File(dir, "input.sam");
final File output = new File(dir, "output");
FileHelper.resourceToFile("com/rtg/reader/resources/mated.sam", input);
final String err = checkMainInitBadFlags(input.getPath(), "-o", output.getPath(), "-f", "sam-pe");
TestUtils.containsAll(err, "Multiple read groups present in the input file");
}
}
public void testInterleavedFastq() throws Exception {
try (final TestDirectory tempDir = new TestDirectory("format")) {
final File input = new File(tempDir, "input.fastq");
FileHelper.resourceToFile("com/rtg/reader/resources/interleaved.fastq", input);
final File output = new File(tempDir, "output");
final MainResult res = checkMainInit("-o", output.getPath(), "-f", "fastq-interleaved", input.getPath());
mNano.check("format-interleaved.txt", StringUtils.grepMinusV(res.out(), "SDF-ID|Processing"));
assertTrue(output.isDirectory());
assertTrue(new File(output, "left").isDirectory());
assertTrue(new File(output, "right").isDirectory());
assertTrue(new File(new File(output, "left"), "mainIndex").exists());
assertTrue(new File(new File(output, "right"), "mainIndex").exists());
final File progress = new File(output, "progress");
assertTrue(progress.exists());
final String prog = FileUtils.fileToString(progress);
TestUtils.containsAll(prog, "Formatting interleaved paired-end FASTQ data", "Finished successfully");
}
}
}
| UTF-8 | Java | 34,382 | java | FormatCliTest.java | Java | []
| null | []
| /*
* Copyright (c) 2014. Real Time Genomics Limited.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.rtg.reader;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import com.rtg.launcher.AbstractCli;
import com.rtg.launcher.AbstractCliTest;
import com.rtg.launcher.MainResult;
import com.rtg.mode.DNAFastaSymbolTable;
import com.rtg.reader.FormatCli.BadFormatCombinationException;
import com.rtg.reader.FormatCli.PrereadExecutor;
import com.rtg.reader.FormatCli.PrereadExecutor.SequenceProcessor;
import com.rtg.util.Constants;
import com.rtg.util.License;
import com.rtg.util.StringUtils;
import com.rtg.util.TestUtils;
import com.rtg.util.cli.CFlags;
import com.rtg.util.diagnostic.Diagnostic;
import com.rtg.util.diagnostic.NoTalkbackSlimException;
import com.rtg.util.intervals.LongRange;
import com.rtg.util.io.FileUtils;
import com.rtg.util.io.MemoryPrintStream;
import com.rtg.util.io.TestDirectory;
import com.rtg.util.test.FileHelper;
/**
* Test class for corresponding class.
*/
public class FormatCliTest extends AbstractCliTest {
@Override
protected AbstractCli getCli() {
return new FormatCli();
}
public void testHelp() {
checkHelp("rtg format"
, "Converts the contents of sequence data files (FASTA/FASTQ/SAM/BAM) into the RTG Sequence Data File (SDF) format."
, "-f,", "--format=FORMAT", "format of input. Allowed values are [fasta, fastq"
, "-q", "--quality-format=FORMAT", "quality data encoding", "Allowed values are [sanger, solexa, illumina] (Default is sanger)"
, "--input-list-file=FILE", "file containing a list of input read files (1 per line)"
, "-l,", "--left=FILE", "left input file for FASTA/FASTQ paired end data"
, "-o,", "--output=SDF", "name of output SDF"
, "-p,", "--protein", "input is protein. If this option is not specified, then the input is assumed to consist of nucleotides"
, "-r,", "--right=FILE", "right input file for FASTA/FASTQ paired end data"
, "FILE+", "input sequence files. May be specified 0 or more times"
, "--duster", "treat lower case residues as unknowns"
, "--exclude=STRING", "exclude input sequences based on their name. If the input sequence contains the specified string then that sequence is excluded from the SDF. May be specified 0 or more times"
, "--no-names", "do not include name data in the SDF output"
, "--no-quality", "do not include quality data in the SDF output"
, "--allow-duplicate-names"
, "--sam-rg"
, "--select-read-group"
);
checkExtendedHelp("rtg format"
, "--Xcompress=BOOL", "compress sdf (Default is " + true + ")"
);
}
public void testCFlagsQ() throws Exception {
Diagnostic.setLogStream();
final File dir = FileUtils.createTempDir("formattest", "badfiles");
try {
final File xx = new File(dir, "xx");
FileUtils.stringToFile("", xx);
final File nsd = new File(dir, "no-such-dir");
checkHandleFlagsOut("-p", "-o", nsd.getPath(), "-f", "fastq", "-q", "sanger", xx.getPath());
final CFlags flags = getCFlags();
assertTrue(flags.isSet("protein"));
assertEquals("fastq", flags.getValue("format"));
assertEquals(nsd.getPath(), ((File) flags.getValue("output")).getPath());
assertEquals(xx, flags.getAnonymousFlag(0).getValue());
} finally {
assertTrue(FileHelper.deleteAll(dir));
}
}
private static final String JUNITOUT = ".junitout";
private static final String EXPECTED_MSG = "" + StringUtils.LS
+ "Format : FASTA" + StringUtils.LS
+ "Type : DNA" + StringUtils.LS
+ "Number of sequences: 2" + StringUtils.LS
+ "Total residues : 10" + StringUtils.LS
+ "Minimum length : 5" + StringUtils.LS
+ "Mean length : 5" + StringUtils.LS
+ "Maximum length : 5" + StringUtils.LS;
public void testValidUseA() throws Exception {
try (final TestDirectory tempDir = new TestDirectory("format")) {
final File raw = new File(tempDir, "test");
final File outputDir = new File(tempDir, JUNITOUT);
FileUtils.stringToFile(">x\naCTGN\n>y\nACTGN\n", raw);
testValidUse(new String[] {"-o", outputDir.getPath(), raw.getPath(), "--duster", "--exclude", "y"}, outputDir);
}
}
public void testValidUseAList() throws Exception {
try (final TestDirectory tempDir = new TestDirectory("format")) {
final File raw = new File(tempDir, "test");
final File outputDir = new File(tempDir, JUNITOUT);
FileUtils.stringToFile(">x\naCTGN\n>y\nACTGN\n", raw);
final File list = new File(tempDir, "list");
FileUtils.stringToFile(raw.getPath(), list);
testValidUse(new String[]{"-o", outputDir.getPath(), "-I", list.getPath(), "--duster", "--exclude", "y"}, outputDir);
}
}
private void testValidUse(String[] args, File outputDir) throws IOException {
try (final TestDirectory tempDir = new TestDirectory("format")) {
final String outStr = checkMainInitOk(args);
TestUtils.containsAll(outStr, EXPECTED_MSG
, "Formatting FASTA data"
, "Input Data"
, "Files : "
, StringUtils.LS + StringUtils.LS + "Output Data"
, "SDF-ID : "
, "Number of sequences: 1" + StringUtils.LS
+ "Total residues : 5" + StringUtils.LS
+ "Minimum length : 5" + StringUtils.LS
+ "Mean length : 5" + StringUtils.LS
+ "Maximum length : 5" + StringUtils.LS
+ StringUtils.LS
+ "There were 1 sequences skipped due to filters" + StringUtils.LS
+ "There were 1 residues converted from lower case to unknowns");
assertTrue(outputDir.isDirectory());
assertTrue(new File(outputDir, "mainIndex").exists());
final File summary = new File(outputDir, "summary.txt");
assertTrue(summary.exists());
final String sum = FileUtils.fileToString(summary);
assertTrue(sum, sum.contains(EXPECTED_MSG));
final File progress = new File(outputDir, "progress");
assertTrue(progress.exists());
final String prog = FileUtils.fileToString(progress);
TestUtils.containsAll(prog, "Formatting FASTA data");
final File outf = new File(tempDir, "out.fasta");
MainResult.run(new Sdf2Fasta(), "-o", outf.getPath(), "-i", outputDir.getPath(), "-Z");
assertTrue(outf.exists());
assertFalse(outf.isDirectory());
try (BufferedReader r = new BufferedReader(new FileReader(outf))) {
assertEquals(">x", r.readLine());
assertEquals("NCTGN", r.readLine());
assertNull(r.readLine());
}
}
}
public void testDuplicateError() throws Exception {
Diagnostic.setLogStream();
try (final TestDirectory tempDir = new TestDirectory("format")) {
final File inputA = new File(tempDir, "inputA.fasta");
final File inputB = new File(tempDir, "inputB.fasta");
FileUtils.stringToFile(">x\nactgn" + StringUtils.LS, inputA);
FileUtils.stringToFile(">y\nactgn" + StringUtils.LS + ">x\nactgn" + StringUtils.LS, inputB);
final File outputDir = new File(tempDir, "output");
final File dupFile = new File(outputDir.getAbsolutePath(), "duplicate-names.txt");
final String err = checkMainInitWarn("-o", outputDir.getAbsolutePath(), inputA.getAbsolutePath(), inputB.getAbsolutePath());
assertTrue(outputDir.exists());
assertTrue(dupFile.exists());
assertTrue(err.contains("Duplicate Sequence Names in Input"));
assertEquals("x" + StringUtils.LS, FileUtils.fileToString(dupFile));
}
}
public void testValidUseQ() throws Exception {
try (final TestDirectory tempDir = new TestDirectory("format")) {
final File raw = new File(tempDir, "raw");
FileUtils.stringToFile("@x\n" + "actgn\n" + "+x\n" + "ACTGN\n", raw);
final File outputDir = new File(tempDir, JUNITOUT);
final String bout = checkMainInitOk("-o", outputDir.getPath(), "-f", "fastq", "-q", "sanger", raw.getPath());
mNano.check("format-useq.txt", StringUtils.grepMinusV(bout, "SDF-ID|Processing|Formatting FASTQ"));
assertTrue(outputDir.isDirectory());
assertTrue(new File(outputDir, "mainIndex").exists());
final File summary = new File(outputDir, "summary.txt");
assertTrue(summary.exists());
final String sum = FileUtils.fileToString(summary);
mNano.check("format-useq.txt", StringUtils.grepMinusV(sum, "SDF-ID"));
final File outf = new File(tempDir, "out.fasta");
//System.err.println("bos 1 ' " + bos.toString());
MainResult res = MainResult.run(new SdfStatistics(), outputDir.getAbsolutePath());
assertEquals(res.err(), 0, res.rc());
assertTrue(res.out().contains("Sequence names : yes"));
assertTrue(res.out().contains("Residue qualities : yes"));
res = MainResult.run(new Sdf2Fasta(), "-o", outf.getPath(), "-i", outputDir.getPath(), "-Z");
assertEquals(res.err(), 0, res.rc());
assertEquals(0, res.out().length());
assertTrue(outf.exists());
assertFalse(outf.isDirectory());
try (BufferedReader r = new BufferedReader(new FileReader(outf))) {
assertEquals(">x", r.readLine());
assertEquals("ACTGN", r.readLine());
assertNull(r.readLine());
}
}
}
public void testNoNames() throws Exception {
try (final TestDirectory tempDir = new TestDirectory("format")) {
final File raw = new File(tempDir, "raw");
FileUtils.stringToFile("@x\n" + "actgn\n" + "+x\n" + "ACTGN\n", raw);
final File outputDir = new File(tempDir, JUNITOUT);
checkMainInitOk("-o", outputDir.getPath(), "-f", "fastq", "-q", "sanger", raw.getPath(), "--no-names");
final MainResult res = MainResult.run(new SdfStatistics(), outputDir.getAbsolutePath());
assertEquals(res.err(), 0, res.rc());
assertTrue(res.out(), res.out().contains("Sequence names : no"));
}
}
public void testNoQuality() throws Exception {
try (final TestDirectory tempDir = new TestDirectory("format")) {
final File raw = new File(tempDir, "raw");
FileUtils.stringToFile("@x\n" + "actgn\n" + "+x\n" + "ACTGN\n", raw);
final File outputDir = new File(tempDir, JUNITOUT);
checkMainInitOk("-o", outputDir.getPath(), "-f", "fastq", "-q", "sanger", raw.getPath(), "--no-quality");
final MainResult res = MainResult.run(new SdfStatistics(), outputDir.getAbsolutePath());
assertEquals(res.err(), 0, res.rc());
assertTrue(res.out(), res.out().contains("Residue qualities : no"));
}
}
public void testValidUsePaired() throws Exception {
try (final TestDirectory tempDir = new TestDirectory("format")) {
final File raw1 = new File(tempDir, "raw1");
final File raw2 = new File(tempDir, "raw2");
FileUtils.stringToFile(">x\n" + "aCTGN\n>y\nACTGN\n", raw1);
FileUtils.stringToFile(">x\n" + "ACTGN\n>y\nACTGN\n", raw2);
final File outputDir = new File(tempDir, JUNITOUT);
final MainResult res = runFormat(outputDir, "@RG\tID:id\tSM:sm\tPL:ILLUMINA",
"-o", outputDir.getPath(), "-f", "fasta", "-l" , raw1.getPath(), "-r", raw2.getPath(), "--duster", "--exclude", "y", "--sam-rg", "@RG\\tID:id\\tSM:sm\\tPL:ILLUMINA");
TestUtils.containsAll(res.out()
, "Formatting paired-end FASTA data"
, "Input Data" + StringUtils.LS
+ "Files : raw1 raw2" + StringUtils.LS
+ "Format : paired-end FASTA" + StringUtils.LS
+ "Type : DNA" + StringUtils.LS
+ "Number of pairs : 2" + StringUtils.LS
+ "Number of sequences: 4" + StringUtils.LS
+ "Total residues : 20" + StringUtils.LS
+ "Minimum length : 5" + StringUtils.LS
+ "Mean length : 5" + StringUtils.LS
+ "Maximum length : 5" + StringUtils.LS
+ StringUtils.LS
+ "Output Data" + StringUtils.LS
+ "SDF-ID : "
, "Number of pairs : 1" + StringUtils.LS
+ "Number of sequences: 2" + StringUtils.LS
+ "Total residues : 10" + StringUtils.LS
+ "Minimum length : 5" + StringUtils.LS
+ "Mean length : 5" + StringUtils.LS
+ "Maximum length : 5" + StringUtils.LS
+ StringUtils.LS
+ "There were 1 pairs skipped due to filters" + StringUtils.LS
+ "There were 1 residues converted from lower case to unknowns" + StringUtils.LS
);
assertTrue(outputDir.isDirectory());
assertTrue(new File(outputDir, "left").isDirectory());
assertTrue(new File(outputDir, "right").isDirectory());
assertTrue(new File(new File(outputDir, "left"), "mainIndex").exists());
assertTrue(new File(new File(outputDir, "right"), "mainIndex").exists());
final File progress = new File(outputDir, "progress");
assertTrue(progress.exists());
final String prog = FileUtils.fileToString(progress);
TestUtils.containsAll(prog, "Formatting paired-end FASTA data", "paired-end SDF");
}
}
public void testUnevenPaired() throws Exception {
try (final TestDirectory tempDir = new TestDirectory("format")) {
final File rawLeft = new File(tempDir, "left.fasta");
final File rawRight = new File(tempDir, "right.fasta");
FileUtils.stringToFile("@x\n" + "actgn\n" + "+x\n" + "ACTGN\n@x2\n" + "actgn\n" + "+x2\n" + "ACTGN\n", rawLeft);
FileUtils.stringToFile("@x\n" + "actgn\n" + "+x\n" + "ACTGN\n", rawRight);
final MemoryPrintStream out = new MemoryPrintStream();
final MemoryPrintStream err = new MemoryPrintStream();
final File outputDir = new File(tempDir, JUNITOUT);
final String s = checkMainInitBadFlags("-o", outputDir.getPath(), "-f", "fastq", "-q", "sanger", "-l", rawLeft.getPath(), "-r", rawRight.getPath());
assertTrue(outputDir.isDirectory());
assertTrue(new File(outputDir, "left").isDirectory());
assertTrue(new File(outputDir, "right").isDirectory());
assertTrue(new File(new File(outputDir, "left"), "mainIndex").exists());
assertTrue(new File(new File(outputDir, "right"), "mainIndex").exists());
assertTrue(s, s.contains("Invalid input, paired end data must have same number of sequences. Left had: 2 Right had: 1"));
out.close();
err.close();
}
}
public void testValidUseCG() throws Exception {
if (License.isDeveloper()) {
try (final TestDirectory tempDir = new TestDirectory("format")) {
final File raw1 = new File(tempDir, "raw1.fq");
final File raw2 = new File(tempDir, "raw2.fq");
FileUtils.stringToFile("@x\n" + "actgn\n" + "+x\n" + "ACTGN\n", raw1);
FileUtils.stringToFile("@x\n" + "actgn\n" + "+x\n" + "ACTGN\n", raw2);
final File outputDir = new File(tempDir, JUNITOUT);
final String out = checkMainInitOk("-o", outputDir.getPath(), "-f", "fastq-cg", "-l", raw1.getPath(), "-r", raw2.getPath());
assertTrue(out.contains("Format : paired-end FASTQ-CG"));
assertTrue(out.contains("Type : DNA"));
assertTrue(out.contains("SDF-ID"));
assertTrue(out.contains("Number of sequences: 2"));
assertTrue(out.contains("Total residues : 10"));
assertTrue(out.contains("Minimum length : 5"));
assertTrue(out.contains("Maximum length : 5"));
assertTrue(outputDir.isDirectory());
assertTrue(new File(outputDir, "left").isDirectory());
assertTrue(new File(outputDir, "right").isDirectory());
assertTrue(new File(new File(outputDir, "left"), "mainIndex").exists());
assertTrue(new File(new File(outputDir, "right"), "mainIndex").exists());
}
}
}
public void testValidUseProtein() throws Exception {
try (TestDirectory tempDir = new TestDirectory("format")) {
final File raw = new File(tempDir, "in.fasta");
FileUtils.stringToFile(">x\nX*ARNDCQEGHILKMFPSTWYV\n", raw);
final File outputDir = new File(tempDir, JUNITOUT);
final String outStr = checkMainInitOk("-o", outputDir.getPath(), "-p", raw.getPath());
mNano.check("format-useprotein.txt", StringUtils.grepMinusV(outStr, "SDF-ID|Processing|Formatting FASTA"));
assertTrue(outputDir.isDirectory());
assertTrue(new File(outputDir, "mainIndex").exists());
final File summary = new File(outputDir, "summary.txt");
assertTrue(summary.exists());
final String sum = FileUtils.fileToString(summary);
mNano.check("format-useprotein.txt", StringUtils.grepMinusV(sum, "SDF-ID"));
final File outf = new File(tempDir, "out.fasta");
final MainResult res = MainResult.run(new Sdf2Fasta(), "-o", outf.getPath(), "-i", outputDir.getPath(), "-Z");
assertEquals(0, res.out().length());
assertTrue(outf.exists());
assertFalse(outf.isDirectory());
try (BufferedReader r = new BufferedReader(new FileReader(outf))) {
assertEquals(">x", r.readLine());
assertEquals("X*ARNDCQEGHILKMFPSTWYV", r.readLine());
assertNull(r.readLine());
}
}
}
public void testBadUse() {
final String e = checkMainInitBadFlags("--no-such-option");
assertTrue(e.contains("Error: Unknown flag --no-such-option"));
}
private static final String EXPECTED_ERROR2 = "Error: File not found: \"" + File.separator + "in_a_small_hole_lived_a_hobbit\"" + StringUtils.LS
+ "Error: There were 1 invalid input file paths" + StringUtils.LS;
public void testBadFiles() throws Exception {
try (TestDirectory dir = new TestDirectory("format")) {
final File out = new File(dir, "prereadertestshouldnthappen");
final String e = checkMainInitBadFlags("-o", out.getPath(), File.separator + "in_a_small_hole_lived_a_hobbit");
assertEquals(e, EXPECTED_ERROR2, e);
}
}
public void testInputTestingFlags() throws IOException {
Diagnostic.setLogStream();
try (TestDirectory dir = new TestDirectory("format")) {
final File input = new File(dir, "in");
FileUtils.stringToFile("", input);
final File outDir = new File(dir, "out");
TestUtils.containsAllUnwrapped(checkHandleFlagsErr("-o", outDir.getPath()), "No input files specified.");
TestUtils.containsAllUnwrapped(checkHandleFlagsErr("-o", outDir.getPath(), "-l", input.getPath()), "Both left and right reads must be specified.");
TestUtils.containsAllUnwrapped(checkHandleFlagsErr("-o", outDir.getPath(), "-r", input.getPath()), "Both left and right reads must be specified.");
TestUtils.containsAllUnwrapped(checkHandleFlagsErr("-o", outDir.getPath(), "-l", input.getPath(), "-r", input.getPath(), "-p"), "Cannot set protein flag when left and right files are specified.");
TestUtils.containsAllUnwrapped(checkHandleFlagsErr("-o", outDir.getPath(), "-l", input.getPath(), input.getPath()), "Either specify individual input files or left and right files, not both.");
TestUtils.containsAllUnwrapped(checkHandleFlagsErr("-o", outDir.getPath(), "-r", input.getPath(), input.getPath()), "Either specify individual input files or left and right files, not both.");
}
}
public void testFormatflag() throws IOException {
Diagnostic.setLogStream();
try (TestDirectory que = new TestDirectory("format")) {
final File f = new File(que, "in");
FileUtils.stringToFile("", f);
final String[] args = {
"-o", "res",
f.getPath(),
"-f", "embl"
};
final String err = checkHandleFlagsErr(args);
assertTrue(err, err.contains("Invalid value \"embl\" for flag -f"));
}
}
public void testOutputflag() throws IOException {
Diagnostic.setLogStream();
final File que = FileUtils.createTempDir("format", "pre");
final File i = new File(que, "test");
assertTrue(i.createNewFile());
final String[] args = {
"-o", que.getPath(),
i.getPath(),
};
final String result = checkHandleFlagsErr(args);
TestUtils.containsAllUnwrapped(result, "The directory \"" + que.getPath() + "\" already exists. Please remove it first or choose a different directory.");
FileHelper.deleteAll(que);
}
public void testOutputAsFileflag() throws IOException {
Diagnostic.setLogStream();
try (TestDirectory dir = new TestDirectory("format")) {
final File que = new File(dir, "query");
FileUtils.stringToFile("", que);
final String[] args = {
"-o", que.getPath(),
que.getPath(),
};
final String result = checkHandleFlagsErr(args);
TestUtils.containsAllUnwrapped(result, "The directory \"" + que.getPath() + "\" already exists. Please remove it first or choose a different directory.");
}
}
public void testSolexa13Format() throws Exception {
try (TestDirectory tempDir = new TestDirectory("format")) {
final File outputDir = new File(tempDir, JUNITOUT);
final File input = new File(tempDir, "in");
FileUtils.stringToFile("^", input);
String err = checkMainInitBadFlags("-o", outputDir.getPath(), "-f", "fastq", "-q", "solexa1.2", input.getPath());
assertTrue("error was: " + err, err.contains("Invalid value \"solexa1.2\" for flag -q."));
err = checkMainInitBadFlags("-o", outputDir.getPath(), "-f", "fastq", "-q", "illumina", input.getPath());
assertTrue("error was: " + err, err.contains("Unrecognized symbols appeared before label symbol. Last sequence read was: \"<none>\""));
}
}
public void testErrorHandling() throws IOException {
try (final TestDirectory tempDir = new TestDirectory("format")) {
final File outputDir = new File(tempDir, JUNITOUT);
final File raw = new File(tempDir, "test");
FileUtils.stringToFile(">x\nX*ARNDCQEGHILKMFPSTWYV\n", raw);
String err = checkMainInitBadFlags("-o", outputDir.getPath(), "-f", "fastq", "-q", "sanger", "-p", raw.getPath());
TestUtils.containsAll(err, "Incompatible sequence type and file format. format=FASTQ protein=" + true);
final File outputDir2 = new File(tempDir, "blah");
err = checkMainInitBadFlags("-o", outputDir2.getPath(), "-f", "fasta", "--trim-threshold", "15", "-p", raw.getPath());
TestUtils.containsAll(err, "Input must contain qualities to perform quality-based read trimming.");
}
}
public void testGetFormat() {
assertEquals(SourceFormat.FASTA, FormatCli.getFormat("fasta", null, true, false).getSourceFormat());
assertEquals(SourceFormat.FASTQ, FormatCli.getFormat("fastq", "sanger", true, false).getSourceFormat());
assertEquals(QualityFormat.SOLEXA, FormatCli.getFormat("fastq", "solexa", true, false).getQualityFormat());
assertEquals(QualityFormat.SOLEXA1_3, FormatCli.getFormat("fastq", "illumina", true, false).getQualityFormat());
try {
FormatCli.getFormat("blah", null, true, false);
} catch (final NoTalkbackSlimException e) {
assertEquals("Invalid file format=blah", e.getMessage());
}
}
public void testSequenceProcessor() throws IOException {
final File dir = FileUtils.createTempDir("test", "number");
try {
final List<InputStream> list = new ArrayList<>();
final SequenceProcessor p = new SequenceProcessor(new FastaSequenceDataSource(list, new DNAFastaSymbolTable()), PrereadType.UNKNOWN, PrereadArm.UNKNOWN, dir, null, null, false, null);
assertEquals(Constants.MAX_FILE_SIZE, p.mWriter.getSizeLimit());
} finally {
FileHelper.deleteAll(dir);
}
}
private static final DataSourceDescription FASTQ_DS = new DataSourceDescription(SourceFormat.FASTQ, QualityFormat.SANGER, false, false, false);
public void testBadFormatCombinationException() throws IOException {
Diagnostic.setLogStream();
final PrereadExecutor ex = new PrereadExecutor(true, false, FASTQ_DS, null, null, null, false, false, false, true, null, null, false);
try {
ex.performPreread(null);
fail();
} catch (final BadFormatCombinationException e) {
assertEquals("Incompatible sequence type and file format. format=FASTQ protein=" + true, e.getMessage());
}
}
public void testFormattingMessage() {
testMessage("FASTQ-CG", new DataSourceDescription(SourceFormat.FASTQ, QualityFormat.UNKNOWN, true, false, true));
testMessage("FASTA", new DataSourceDescription(SourceFormat.FASTA, QualityFormat.UNKNOWN, false, false, false));
testMessage("FASTQ", FASTQ_DS);
testMessage("FASTQ-SOLEXA", new DataSourceDescription(SourceFormat.FASTQ, QualityFormat.SOLEXA, false, false, false));
testMessage("FASTQ-SOLEXA1_3", new DataSourceDescription(SourceFormat.FASTQ, QualityFormat.SOLEXA1_3, false, false, false));
testMessage("SAM/BAM", new DataSourceDescription(SourceFormat.SAM, QualityFormat.SANGER, true, false, false));
testMessage("SAM/BAM", new DataSourceDescription(SourceFormat.SAM, QualityFormat.SANGER, false, false, false));
}
private void testMessage(String formatString, DataSourceDescription desc) {
if (desc.isPairedEnd()) {
assertEquals("Formatting paired-end " + formatString + " data", FormatCli.PrereadExecutor.formattingMessage(desc));
} else {
assertEquals("Formatting " + formatString + " data", FormatCli.PrereadExecutor.formattingMessage(desc));
}
}
public void testSamRGFormat() throws IOException {
try (TestDirectory dir = new TestDirectory()) {
final File input = new File(dir, "input.sam");
final File output = new File(dir, "output");
FileHelper.resourceToFile("com/rtg/sam/resources/mated.sam", input);
runFormat(output, "@RG\tID:rg1\tSM:sm1\tPL:ILLUMINA",
input.getPath(), "-o", output.getPath(), "-f", "sam-pe");
}
}
public void testSamRGFormatCustom() throws IOException {
try (TestDirectory dir = new TestDirectory()) {
final File input = new File(dir, "input.sam");
final File output = new File(dir, "output");
final String custom = "@RG\tID:rg999\tPL:NOT_ILLUMINA\tSM:sample".replaceAll("\t", "\\\\t");
FileHelper.resourceToFile("com/rtg/sam/resources/mated.sam", input);
runFormat(output, "@RG\tID:rg999\tPL:NOT_ILLUMINA\tSM:sample",
input.getPath(), "-o", output.getPath(), "-f", "sam-pe", "--sam-rg", custom);
}
}
private MainResult runFormat(File output, String expected, String... args) throws IOException {
final MainResult res = checkMainInit(args);
final DefaultSequencesReader leftReader = new DefaultSequencesReader(new File(output, "left"), LongRange.NONE);
assertEquals(expected, leftReader.samReadGroup());
final DefaultSequencesReader rightReader = new DefaultSequencesReader(new File(output, "right"), LongRange.NONE);
assertEquals(expected, rightReader.samReadGroup());
return res;
}
public void testSamRGFormatMultiple() throws IOException {
try (TestDirectory dir = new TestDirectory()) {
final File input = new File(dir, "input.sam");
final File output = new File(dir, "output");
FileHelper.resourceToFile("com/rtg/reader/resources/mated.sam", input);
runFormat(output, "@RG\tID:rg2\tSM:doggy\tPL:Sturdy",
input.getPath(), "-o", output.getPath(), "-f", "sam-pe", "--select-read-group", "rg2");
}
}
public void testDedupSecondary() throws IOException {
try (TestDirectory dir = new TestDirectory()) {
final File input = new File(dir, "input.sam");
final File output = new File(dir, "output");
FileHelper.resourceToFile("com/rtg/reader/resources/mated.sam", input);
final String err = checkMainInitWarn(input.getPath(), "-o", output.getPath(), "-f", "sam-pe", "--select-read-group", "rg1", "--Xdedup-secondary-alignments");
TestUtils.containsAll(err, "1 reads missing a pair");
try (final DefaultSequencesReader rightReader = new DefaultSequencesReader(new File(output, "right"), LongRange.NONE)) {
assertEquals(2, rightReader.numberSequences());
final StringBuilder sb = new StringBuilder();
final SequencesIterator it = rightReader.iterator();
while (it.nextSequence()) {
sb.append(it.currentName());
}
TestUtils.containsAll(sb.toString(), "48218590", "48851323");
}
}
}
public void testHandleDupAndSupplemental() throws IOException {
try (TestDirectory dir = new TestDirectory()) {
final File input = new File(dir, "input.sam");
final File output = new File(dir, "output");
FileHelper.resourceToFile("com/rtg/reader/resources/mated-dups.sam", input);
final String err = checkMainInitWarn(input.getPath(), "-o", output.getPath(), "-f", "sam-pe", "--select-read-group", "rg1", "--Xdedup-secondary-alignments");
TestUtils.containsAll(err, "Read 48851323 is duplicated in SAM input", "1 reads missing a pair", "1 records ignored as duplicates in input");
try (final DefaultSequencesReader rightReader = new DefaultSequencesReader(new File(output, "right"), LongRange.NONE)) {
assertEquals(2, rightReader.numberSequences());
final StringBuilder sb = new StringBuilder();
final SequencesIterator it = rightReader.iterator();
while (it.nextSequence()) {
sb.append(it.currentName());
}
TestUtils.containsAll(sb.toString(), "48218590", "48851323");
}
}
}
public void testUnmatchableReadGroup() throws IOException {
try (TestDirectory dir = new TestDirectory()) {
final File input = new File(dir, "input.sam");
final File output = new File(dir, "output");
FileHelper.resourceToFile("com/rtg/reader/resources/mated.sam", input);
final String err = checkMainInitBadFlags(input.getPath(), "-o", output.getPath(), "-f", "sam-pe", "--select-read-group", "I am not here");
TestUtils.containsAll(err, "No read group information matching \"I am not here\" present in the input file");
}
}
public void testMultifile() throws IOException {
try (TestDirectory dir = new TestDirectory()) {
final File input = new File(dir, "input.sam");
final File input2 = new File(dir, "input2.sam");
final File output = new File(dir, "output");
FileHelper.resourceToFile("com/rtg/reader/resources/mated.sam", input);
FileHelper.resourceToFile("com/rtg/sam/resources/mated.sam", input2);
runFormat(output, "@RG\tID:rg1\tSM:sm1\tPL:ILLUMINA",
input.getPath(), input2.getPath(), "-o", output.getPath(), "-f", "sam-pe", "--select-read-group", "rg1");
}
}
public void testMultifileMissingFromSecond() throws IOException {
try (TestDirectory dir = new TestDirectory()) {
final File input = new File(dir, "input.sam");
final File input2 = new File(dir, "input2.sam");
final File output = new File(dir, "output");
FileHelper.resourceToFile("com/rtg/reader/resources/mated.sam", input);
FileHelper.resourceToFile("com/rtg/sam/resources/mated.sam", input2);
final String err = checkMainInitBadFlags(input2.getPath(), input.getPath(), "-o", output.getPath(), "-f", "sam-pe", "--select-read-group", "rg2");
TestUtils.containsAll(err, "No read group information matching \"rg2\" present in the input file ");
}
}
public void testSamRGFormatMultipleFail() throws IOException {
try (TestDirectory dir = new TestDirectory()) {
final File input = new File(dir, "input.sam");
final File output = new File(dir, "output");
FileHelper.resourceToFile("com/rtg/reader/resources/mated.sam", input);
final String err = checkMainInitBadFlags(input.getPath(), "-o", output.getPath(), "-f", "sam-pe");
TestUtils.containsAll(err, "Multiple read groups present in the input file");
}
}
public void testInterleavedFastq() throws Exception {
try (final TestDirectory tempDir = new TestDirectory("format")) {
final File input = new File(tempDir, "input.fastq");
FileHelper.resourceToFile("com/rtg/reader/resources/interleaved.fastq", input);
final File output = new File(tempDir, "output");
final MainResult res = checkMainInit("-o", output.getPath(), "-f", "fastq-interleaved", input.getPath());
mNano.check("format-interleaved.txt", StringUtils.grepMinusV(res.out(), "SDF-ID|Processing"));
assertTrue(output.isDirectory());
assertTrue(new File(output, "left").isDirectory());
assertTrue(new File(output, "right").isDirectory());
assertTrue(new File(new File(output, "left"), "mainIndex").exists());
assertTrue(new File(new File(output, "right"), "mainIndex").exists());
final File progress = new File(output, "progress");
assertTrue(progress.exists());
final String prog = FileUtils.fileToString(progress);
TestUtils.containsAll(prog, "Formatting interleaved paired-end FASTQ data", "Finished successfully");
}
}
}
| 34,382 | 0.660753 | 0.655954 | 679 | 49.63623 | 37.93404 | 206 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.391753 | false | false | 13 |
63e0697efb2953d24f0121bee8bcf26e5aea01f3 | 24,970,939,923,768 | 1352d02f029b593a1a338de778099f751aa43351 | /src/main/java/net/dqsy/manager/pojo/Organization.java | 1a9c6eddf96fd05173c5932f19560594e6e798e3 | []
| no_license | cieron7/SUManager | https://github.com/cieron7/SUManager | 90d5148b89605c2aada3e0fea0f833983c8652b4 | 2ebc61a7e92350a79520e35b6011915179232e0a | refs/heads/dev | 2021-01-17T08:47:07.532000 | 2017-05-01T08:13:50 | 2017-05-01T08:13:50 | 84,837,895 | 5 | 3 | null | false | 2017-03-21T17:41:41 | 2017-03-13T14:45:16 | 2017-03-21T09:34:07 | 2017-03-21T17:39:18 | 446 | 2 | 1 | 1 | HTML | null | null | package net.dqsy.manager.pojo;
import java.util.Date;
/**
* 机构(院系)
* Created by Nathan on 2017/3/14.
*/
public class Organization {
private long id; //id
private long accountId; //用户id
private String logo; //logo地址
private String name; //机构(院系)名称
private Date createTime; //创建时间
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public long getAccountId() {
return accountId;
}
public void setAccountId(long accountId) {
this.accountId = accountId;
}
public String getLogo() {
return logo;
}
public void setLogo(String logo) {
this.logo = logo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
}
| UTF-8 | Java | 1,068 | java | Organization.java | Java | [
{
"context": "mport java.util.Date;\n\n/**\n * 机构(院系)\n * Created by Nathan on 2017/3/14.\n */\npublic class Organization {\n\n ",
"end": 90,
"score": 0.999437689781189,
"start": 84,
"tag": "NAME",
"value": "Nathan"
}
]
| null | []
| package net.dqsy.manager.pojo;
import java.util.Date;
/**
* 机构(院系)
* Created by Nathan on 2017/3/14.
*/
public class Organization {
private long id; //id
private long accountId; //用户id
private String logo; //logo地址
private String name; //机构(院系)名称
private Date createTime; //创建时间
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public long getAccountId() {
return accountId;
}
public void setAccountId(long accountId) {
this.accountId = accountId;
}
public String getLogo() {
return logo;
}
public void setLogo(String logo) {
this.logo = logo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
}
| 1,068 | 0.567829 | 0.561047 | 61 | 15.918033 | 15.671103 | 48 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.278689 | false | false | 13 |
fa9f52e447f33a3d18f0fc98edc931d4cf57bae0 | 9,371,618,641,967 | 6431b668292313c7f94c618452219e5460cab35c | /leetcode/L_751.java | dc4d18625ad9f72b569a77451d11af540ccd7b15 | []
| no_license | Nideesh1/Algo | https://github.com/Nideesh1/Algo | 9fe0720b0abdce7caa7049cc8d3107cc9f185c3e | 4777b89bba7da9077c0296d30639102109cbda1d | refs/heads/master | 2023-04-04T07:03:26.837000 | 2023-03-28T01:12:51 | 2023-03-28T01:12:51 | 168,574,552 | 77 | 46 | null | false | 2020-10-03T17:06:36 | 2019-01-31T18:27:40 | 2020-10-01T09:24:07 | 2020-10-03T17:06:36 | 1,331 | 43 | 27 | 0 | Java | false | false | class Solution {
public List<String> ipToCIDR(String ip, int n) {
List<String> res = new ArrayList<>();
String[] ar = ip.split("\\.");
long x = 0;
for(int i = 0; i < ar.length; i++){
x = Integer.parseInt(ar[i]) + x * 256;
}
while(n != 0){
long step = (int) (x & -x);
while(step > n) step /= 2;
res.add(ip(x, (int) step));
x += step;
n -= step;
}
return res;
}
public String ip(long x, int step){
int[] ar = new int[4];
ar[0] = (int) (x & 255); x >>= 8;
ar[1] = (int) (x & 255); x >>= 8;
ar[2] = (int) (x & 255); x >>= 8;
ar[3] = (int) (x & 255); x >>= 8;
int len = 33;
while(step > 0){
len--;
step /= 2;
}
return ar[3] + "."+ ar[2] + "." +ar[1] + "." +ar[0] + "/" + len;
}
}
//https://leetcode.com/problems/ip-to-cidr/
| UTF-8 | Java | 995 | java | L_751.java | Java | []
| null | []
| class Solution {
public List<String> ipToCIDR(String ip, int n) {
List<String> res = new ArrayList<>();
String[] ar = ip.split("\\.");
long x = 0;
for(int i = 0; i < ar.length; i++){
x = Integer.parseInt(ar[i]) + x * 256;
}
while(n != 0){
long step = (int) (x & -x);
while(step > n) step /= 2;
res.add(ip(x, (int) step));
x += step;
n -= step;
}
return res;
}
public String ip(long x, int step){
int[] ar = new int[4];
ar[0] = (int) (x & 255); x >>= 8;
ar[1] = (int) (x & 255); x >>= 8;
ar[2] = (int) (x & 255); x >>= 8;
ar[3] = (int) (x & 255); x >>= 8;
int len = 33;
while(step > 0){
len--;
step /= 2;
}
return ar[3] + "."+ ar[2] + "." +ar[1] + "." +ar[0] + "/" + len;
}
}
//https://leetcode.com/problems/ip-to-cidr/
| 995 | 0.372864 | 0.336683 | 36 | 26.638889 | 17.250044 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.777778 | false | false | 13 |
6fcdba972951c1df7207f83e6c2371c7386072b0 | 13,408,887,961,322 | b33d0508a0c0e99635e4fd1f603d189256f13fb4 | /trunk/src/de/berlios/diffr/inputData/SmallInputDataView.java | dac8ae16468831102cd1b47f5add2e62bcd43a35 | []
| no_license | BackupTheBerlios/diffr-svn | https://github.com/BackupTheBerlios/diffr-svn | 30ff5f52d07aab2d2b8235b08b7df7cbe91b50f4 | 414e835beb0dfd033df20db45c1674dd7221fd51 | refs/heads/master | 2021-01-23T12:11:51.944000 | 2010-03-24T20:28:14 | 2010-03-24T20:28:14 | 40,724,974 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package de.berlios.diffr.inputData;
import java.awt.*;
import de.berlios.diffr.*;
import de.berlios.diffr.inputData.InputDataPartView;
import de.berlios.diffr.inputData.surface.SurfaceView;
public class SmallInputDataView extends View {
private static final long serialVersionUID = 1L;
private InputDataPartView surfaceView;
private InputDataPartView incidentWaveView;
public SmallInputDataView(InputData inputData) {
surfaceView = new SurfaceView(inputData.getSurface());
incidentWaveView = new IncidentWaveView(inputData.getIncidentWave());
inputData.getSurface().addModelChangingListener(new ModelChangingListener() {
public void modelWasChanged(Model m) {
repaint();
}
});
inputData.getIncidentWave().addModelChangingListener(new ModelChangingListener() {
public void modelWasChanged(Model m) {
repaint();
}
});
}
public void paintComponent(Graphics g) {
g.setColor(new Color(0, 0, 0));
int width = g.getClipBounds().width;
int height = g.getClipBounds().height;
g.fillRect(0, 0, width, height);
double scaleX = (this.getWidth()-30) / Math.max(surfaceView.getModelSizeX(), incidentWaveView.getModelSizeX());
double scaleY = this.getHeight() / Math.max(surfaceView.getModelSizeY(), incidentWaveView.getModelSizeY());
double scale = Math.min(scaleX, scaleY);
g.setColor(new Color(100, 120, 100));
surfaceView.drawImage(g, scale);
incidentWaveView.drawImage(g, scale);
g.setColor(new Color(255, 255, 255));
g.drawString("Simple mode", 10, height-10);
}
}
| UTF-8 | Java | 1,563 | java | SmallInputDataView.java | Java | []
| null | []
| package de.berlios.diffr.inputData;
import java.awt.*;
import de.berlios.diffr.*;
import de.berlios.diffr.inputData.InputDataPartView;
import de.berlios.diffr.inputData.surface.SurfaceView;
public class SmallInputDataView extends View {
private static final long serialVersionUID = 1L;
private InputDataPartView surfaceView;
private InputDataPartView incidentWaveView;
public SmallInputDataView(InputData inputData) {
surfaceView = new SurfaceView(inputData.getSurface());
incidentWaveView = new IncidentWaveView(inputData.getIncidentWave());
inputData.getSurface().addModelChangingListener(new ModelChangingListener() {
public void modelWasChanged(Model m) {
repaint();
}
});
inputData.getIncidentWave().addModelChangingListener(new ModelChangingListener() {
public void modelWasChanged(Model m) {
repaint();
}
});
}
public void paintComponent(Graphics g) {
g.setColor(new Color(0, 0, 0));
int width = g.getClipBounds().width;
int height = g.getClipBounds().height;
g.fillRect(0, 0, width, height);
double scaleX = (this.getWidth()-30) / Math.max(surfaceView.getModelSizeX(), incidentWaveView.getModelSizeX());
double scaleY = this.getHeight() / Math.max(surfaceView.getModelSizeY(), incidentWaveView.getModelSizeY());
double scale = Math.min(scaleX, scaleY);
g.setColor(new Color(100, 120, 100));
surfaceView.drawImage(g, scale);
incidentWaveView.drawImage(g, scale);
g.setColor(new Color(255, 255, 255));
g.drawString("Simple mode", 10, height-10);
}
}
| 1,563 | 0.731286 | 0.712092 | 41 | 36.121952 | 27.572693 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.560976 | false | false | 13 |
b57547f3cc6733901fe163637d63d4073675f53e | 4,191,888,125,042 | cb859612ec37f3e1c7ae2d2890c3436c5aeaab38 | /TablePlus/src/com/unito/tableplus/server/services/MessagingServiceImpl.java | 4eb60dada0998fcba12c2bc28dcf1a5b728fa2b0 | []
| no_license | giopetrone/personalcloudsyncfr | https://github.com/giopetrone/personalcloudsyncfr | 8a02931d72f4bd3d5a476dd2212c3ae7167da6f9 | 4f61fa4a702222b7b7ea47b1cdf66562abdae558 | refs/heads/master | 2021-01-25T05:34:16.984000 | 2013-10-27T16:29:01 | 2013-10-27T16:29:01 | 32,387,156 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.unito.tableplus.server.services;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.json.JSONException;
import org.json.JSONObject;
import com.google.appengine.api.channel.ChannelFailureException;
import com.google.appengine.api.channel.ChannelMessage;
import com.google.appengine.api.channel.ChannelService;
import com.google.appengine.api.mail.MailService;
import com.google.appengine.api.mail.MailService.Message;
import com.google.appengine.api.mail.MailServiceFactory;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.unito.tableplus.client.services.MessagingService;
import com.unito.tableplus.server.persistence.InvitationQueries;
import com.unito.tableplus.server.persistence.TableQueries;
import com.unito.tableplus.server.persistence.UserQueries;
import com.unito.tableplus.server.util.ServiceFactory;
import com.unito.tableplus.server.util.Utility;
import com.unito.tableplus.shared.model.ChannelMessageType;
import com.unito.tableplus.shared.model.Invitation;
import com.unito.tableplus.shared.model.Table;
import com.unito.tableplus.shared.model.User;
public class MessagingServiceImpl extends RemoteServiceServlet implements
MessagingService {
private static final long serialVersionUID = 1093735951433111434L;
private static final ChannelService channelService = ServiceFactory
.getChannelService();
/**
* The following map contains the connected users lists,
* where the key is the table key and the ArrayList is the list
* of connected users, meant as users using the Channel Service.
*/
private final static Map<Long, ArrayList<Long>> connectedUsers = new HashMap<Long, ArrayList<Long>>();
@Override
public String createChannel(String userId) {
String token = null;
try {
token = channelService.createChannel(userId);
} catch (ChannelFailureException channelFailureException) {
System.err.println("Error creating the channel: "
+ channelFailureException);
} catch (Exception otherException) {
System.err.println("Unknown exception while creating channel: "
+ otherException);
}
return token;
}
@Override
public String sendMessage(Long senderId, String content,
ChannelMessageType type, Long table) {
try {
JSONObject jsonMessage = new JSONObject();
jsonMessage.put("senderId", senderId);
jsonMessage.put("type", type.toString());
jsonMessage.put("content", content);
jsonMessage.put("tableKey", table);
String message = jsonMessage.toString();
ArrayList<Long> recipients = connectedUsers.get(table);
if (recipients != null) {
for (Long r : recipients)
channelService.sendMessage(new ChannelMessage(r.toString(),
message));
}
//TODO avoid this if
if (type.equals(ChannelMessageType.NEWTABLEMEMBER))
channelService
.sendMessage(new ChannelMessage(content, message));
return "Message sent: " + jsonMessage;
} catch (JSONException e) {
return "Error creating JSON on server: " + e;
}
}
/**
* Adds a user to the list of connected users
*
* @param user
* The user id to add to the list.
*/
public static void userConnection(Long userKey) {
User u = UserQueries.queryUser(userKey);
List<Table> tables = TableQueries.queryTables(u.getTables());
try {
JSONObject jsonMessage = new JSONObject();
jsonMessage.put("senderId", userKey);
jsonMessage
.put("type", ChannelMessageType.NEWCONNECTION.toString());
jsonMessage.put("content", "");
for (Table t : tables) {
List<Long> recipients = connectedUsers.get(t.getKey());
if (recipients != null) {
jsonMessage.put("tableKey", t.getKey());
for (Long r : recipients)
channelService.sendMessage(new ChannelMessage(r
.toString(), jsonMessage.toString()));
recipients.add(userKey);
} else {
ArrayList<Long> list = new ArrayList<Long>();
list.add(userKey);
connectedUsers.put(t.getKey(), list);
}
}
} catch (JSONException e) {
System.err.println("Error creating JSON on server: " + e);
}
}
/**
* Removes the user passed as parameter from the list of connected users if
* it exists. Then sends a message to notify other users.
*
* @param user
* The user id to remove.
*/
public static void userDisconnection(Long userKey) {
User u = UserQueries.queryUser(userKey);
List<Table> tables = TableQueries.queryTables(u.getTables());
try {
JSONObject jsonMessage = new JSONObject();
jsonMessage.put("senderId", userKey);
jsonMessage
.put("type", ChannelMessageType.DISCONNECTION.toString());
jsonMessage.put("content", "");
for (Table t : tables) {
ArrayList<Long> recipients = connectedUsers.get(t.getKey());
if (recipients != null) {
jsonMessage.put("tableKey", t.getKey());
recipients.remove(userKey);
for (Long r : recipients)
channelService.sendMessage(new ChannelMessage(r
.toString(), jsonMessage.toString()));
}
}
} catch (JSONException e) {
System.err.println("Error creating JSON on server: " + e);
}
}
@Override
public boolean sendInvitationEmail(String sender, String recipient,
Long tableKey) {
String code = UUID.randomUUID().toString();
Long author = UserQueries.queryUser("email", sender).getKey();
Invitation i = new Invitation();
i.setAuthor(author);
i.setCode(code);
i.setInvitedUser(recipient);
i.setTableKey(tableKey);
try {
MailService mailService = MailServiceFactory.getMailService();
String invitationUrl = Utility.getInvitationServletUrl() + "?code="
+ code;
String body = "You have been invited by "
+ sender
+ " to join his/her table in TablePlusPlus environment. \n"
+ "Don't lose the chance, join now TablePlusPlus and start interacting with "
+ sender
+ " and many others, from all over the world! \n"
+ "Copy-paste in your addresses bar the following address: "
+ invitationUrl;
String subject = "TablePlusPlus - New Invitation";
Message mail = new Message(sender, recipient, subject, body);
mailService.send(mail);
InvitationQueries.storeInvitation(i);
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
}
| UTF-8 | Java | 6,503 | java | MessagingServiceImpl.java | Java | []
| null | []
| package com.unito.tableplus.server.services;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.json.JSONException;
import org.json.JSONObject;
import com.google.appengine.api.channel.ChannelFailureException;
import com.google.appengine.api.channel.ChannelMessage;
import com.google.appengine.api.channel.ChannelService;
import com.google.appengine.api.mail.MailService;
import com.google.appengine.api.mail.MailService.Message;
import com.google.appengine.api.mail.MailServiceFactory;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.unito.tableplus.client.services.MessagingService;
import com.unito.tableplus.server.persistence.InvitationQueries;
import com.unito.tableplus.server.persistence.TableQueries;
import com.unito.tableplus.server.persistence.UserQueries;
import com.unito.tableplus.server.util.ServiceFactory;
import com.unito.tableplus.server.util.Utility;
import com.unito.tableplus.shared.model.ChannelMessageType;
import com.unito.tableplus.shared.model.Invitation;
import com.unito.tableplus.shared.model.Table;
import com.unito.tableplus.shared.model.User;
public class MessagingServiceImpl extends RemoteServiceServlet implements
MessagingService {
private static final long serialVersionUID = 1093735951433111434L;
private static final ChannelService channelService = ServiceFactory
.getChannelService();
/**
* The following map contains the connected users lists,
* where the key is the table key and the ArrayList is the list
* of connected users, meant as users using the Channel Service.
*/
private final static Map<Long, ArrayList<Long>> connectedUsers = new HashMap<Long, ArrayList<Long>>();
@Override
public String createChannel(String userId) {
String token = null;
try {
token = channelService.createChannel(userId);
} catch (ChannelFailureException channelFailureException) {
System.err.println("Error creating the channel: "
+ channelFailureException);
} catch (Exception otherException) {
System.err.println("Unknown exception while creating channel: "
+ otherException);
}
return token;
}
@Override
public String sendMessage(Long senderId, String content,
ChannelMessageType type, Long table) {
try {
JSONObject jsonMessage = new JSONObject();
jsonMessage.put("senderId", senderId);
jsonMessage.put("type", type.toString());
jsonMessage.put("content", content);
jsonMessage.put("tableKey", table);
String message = jsonMessage.toString();
ArrayList<Long> recipients = connectedUsers.get(table);
if (recipients != null) {
for (Long r : recipients)
channelService.sendMessage(new ChannelMessage(r.toString(),
message));
}
//TODO avoid this if
if (type.equals(ChannelMessageType.NEWTABLEMEMBER))
channelService
.sendMessage(new ChannelMessage(content, message));
return "Message sent: " + jsonMessage;
} catch (JSONException e) {
return "Error creating JSON on server: " + e;
}
}
/**
* Adds a user to the list of connected users
*
* @param user
* The user id to add to the list.
*/
public static void userConnection(Long userKey) {
User u = UserQueries.queryUser(userKey);
List<Table> tables = TableQueries.queryTables(u.getTables());
try {
JSONObject jsonMessage = new JSONObject();
jsonMessage.put("senderId", userKey);
jsonMessage
.put("type", ChannelMessageType.NEWCONNECTION.toString());
jsonMessage.put("content", "");
for (Table t : tables) {
List<Long> recipients = connectedUsers.get(t.getKey());
if (recipients != null) {
jsonMessage.put("tableKey", t.getKey());
for (Long r : recipients)
channelService.sendMessage(new ChannelMessage(r
.toString(), jsonMessage.toString()));
recipients.add(userKey);
} else {
ArrayList<Long> list = new ArrayList<Long>();
list.add(userKey);
connectedUsers.put(t.getKey(), list);
}
}
} catch (JSONException e) {
System.err.println("Error creating JSON on server: " + e);
}
}
/**
* Removes the user passed as parameter from the list of connected users if
* it exists. Then sends a message to notify other users.
*
* @param user
* The user id to remove.
*/
public static void userDisconnection(Long userKey) {
User u = UserQueries.queryUser(userKey);
List<Table> tables = TableQueries.queryTables(u.getTables());
try {
JSONObject jsonMessage = new JSONObject();
jsonMessage.put("senderId", userKey);
jsonMessage
.put("type", ChannelMessageType.DISCONNECTION.toString());
jsonMessage.put("content", "");
for (Table t : tables) {
ArrayList<Long> recipients = connectedUsers.get(t.getKey());
if (recipients != null) {
jsonMessage.put("tableKey", t.getKey());
recipients.remove(userKey);
for (Long r : recipients)
channelService.sendMessage(new ChannelMessage(r
.toString(), jsonMessage.toString()));
}
}
} catch (JSONException e) {
System.err.println("Error creating JSON on server: " + e);
}
}
@Override
public boolean sendInvitationEmail(String sender, String recipient,
Long tableKey) {
String code = UUID.randomUUID().toString();
Long author = UserQueries.queryUser("email", sender).getKey();
Invitation i = new Invitation();
i.setAuthor(author);
i.setCode(code);
i.setInvitedUser(recipient);
i.setTableKey(tableKey);
try {
MailService mailService = MailServiceFactory.getMailService();
String invitationUrl = Utility.getInvitationServletUrl() + "?code="
+ code;
String body = "You have been invited by "
+ sender
+ " to join his/her table in TablePlusPlus environment. \n"
+ "Don't lose the chance, join now TablePlusPlus and start interacting with "
+ sender
+ " and many others, from all over the world! \n"
+ "Copy-paste in your addresses bar the following address: "
+ invitationUrl;
String subject = "TablePlusPlus - New Invitation";
Message mail = new Message(sender, recipient, subject, body);
mailService.send(mail);
InvitationQueries.storeInvitation(i);
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
}
| 6,503 | 0.696602 | 0.69368 | 193 | 31.6943 | 23.546774 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.735751 | false | false | 13 |
fa3526620054862967a27dcf5ec2816a4b048563 | 21,698,174,847,329 | 922048f824775fc751cd52f8e7bf624e6494cd2a | /Cao - CS/Ch12_Question15/src/Coin.java | 43f0c8948fbd275e459569942dad66663f5d025f | []
| no_license | ctkhanhly/Java | https://github.com/ctkhanhly/Java | 5163c9912a918cdca536640aecc4d0dae09d66a8 | 4f10b81dd4b8a702fb16e24b29b0dd31aff1e285 | refs/heads/master | 2020-03-31T19:37:23.157000 | 2019-04-04T20:31:08 | 2019-04-04T20:31:08 | 152,504,554 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
public class Coin implements Money{
double value;
public Coin(double value){
this.value = value;
}
public double getAmount(){
return value;
}
}
| UTF-8 | Java | 156 | java | Coin.java | Java | []
| null | []
|
public class Coin implements Money{
double value;
public Coin(double value){
this.value = value;
}
public double getAmount(){
return value;
}
}
| 156 | 0.692308 | 0.692308 | 10 | 14.5 | 12.05197 | 35 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.3 | false | false | 13 |
b6f5e17274f43c8d03626f79f5498b596685f3c1 | 32,865,089,813,345 | d815e7f114927f3c89557a7c1926de90d3986fce | /src/stage/wstp/controllers/users/Disconnect.java | ab0e2a088849aaf04f2ae1b75da2d5521e9811e4 | []
| no_license | emmanuelJd/WSTP | https://github.com/emmanuelJd/WSTP | 097a950a46924970aed9fb0276111859227c7927 | 0bbec661df5d07780b0672cbd18a48f89658996f | refs/heads/master | 2020-04-06T07:12:47.992000 | 2015-03-26T07:26:20 | 2015-03-26T07:26:20 | 32,393,468 | 0 | 1 | null | false | 2015-03-25T13:12:55 | 2015-03-17T13:00:54 | 2015-03-25T08:08:32 | 2015-03-25T13:12:54 | 1,194 | 0 | 1 | 0 | Java | null | null | package stage.wstp.controllers.users;
import java.io.IOException;
import java.util.List;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import stage.wstp.model.daos.TagDAO;
import stage.wstp.model.daos.UserDAO;
import stage.wstp.model.daos.WebServiceDAO;
import stage.wstp.model.entities.WebService;
@WebServlet("/Disconnect")
public class Disconnect extends HttpServlet{
private static final long serialVersionUID = 1L;
@EJB
TagDAO tagDAO;
@EJB
WebServiceDAO wsDAO;
@EJB
UserDAO utilDAO;
public Disconnect() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//déconnection de l'utilisateur
//suppression de la variable de session représentant l'utilisateur
request.getSession().removeAttribute("user");
//récupération des informations sur le nuage de tag
request.setAttribute("TagList",tagDAO.findMostPopularTags());
request.setAttribute("width_canvas_cloud",380);
request.setAttribute("height_canvas_cloud",194);
request.setAttribute("title_cloud","Most popular Tags");
//récupération des 8 derniers web services
List<WebService> wsList = wsDAO.findAllOrderedByDate();
request.setAttribute("wsList", wsList);
request.setAttribute("content","/WEB-INF/views/index.jsp");
this.getServletContext().getRequestDispatcher( "/WEB-INF/views/template.jsp" ).forward( request, response );
}
}
| ISO-8859-1 | Java | 1,835 | java | Disconnect.java | Java | []
| null | []
| package stage.wstp.controllers.users;
import java.io.IOException;
import java.util.List;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import stage.wstp.model.daos.TagDAO;
import stage.wstp.model.daos.UserDAO;
import stage.wstp.model.daos.WebServiceDAO;
import stage.wstp.model.entities.WebService;
@WebServlet("/Disconnect")
public class Disconnect extends HttpServlet{
private static final long serialVersionUID = 1L;
@EJB
TagDAO tagDAO;
@EJB
WebServiceDAO wsDAO;
@EJB
UserDAO utilDAO;
public Disconnect() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//déconnection de l'utilisateur
//suppression de la variable de session représentant l'utilisateur
request.getSession().removeAttribute("user");
//récupération des informations sur le nuage de tag
request.setAttribute("TagList",tagDAO.findMostPopularTags());
request.setAttribute("width_canvas_cloud",380);
request.setAttribute("height_canvas_cloud",194);
request.setAttribute("title_cloud","Most popular Tags");
//récupération des 8 derniers web services
List<WebService> wsList = wsDAO.findAllOrderedByDate();
request.setAttribute("wsList", wsList);
request.setAttribute("content","/WEB-INF/views/index.jsp");
this.getServletContext().getRequestDispatcher( "/WEB-INF/views/template.jsp" ).forward( request, response );
}
}
| 1,835 | 0.745763 | 0.741389 | 60 | 29.466667 | 27.354748 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.116667 | false | false | 13 |
13c9d19c5ab2dea36115ad2b16a8bf3d05901e29 | 16,776,142,284,344 | 3ae8c28ec099f5eb09b2bd6dd77445f4dfc4aa46 | /Activity2_String/String(Activity1).java | a06943be4175d20e74129bd5cbfa02c97c0e08a1 | []
| no_license | shreyansh1406/JavaActivities | https://github.com/shreyansh1406/JavaActivities | f2ff5ff69a1efa4e3e99fd3fb4f956f3ce651cbd | 48443a3bb7cfb5d8f8669fe999cbd14ddd424fa5 | refs/heads/main | 2023-04-04T19:34:18.888000 | 2021-03-05T06:47:14 | 2021-03-05T06:47:14 | 341,852,461 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.*;
public class Main
{
public static void main (String[]args)
{
String s1, s2;
Scanner sc = new Scanner (System.in);
System.out.println ("enter first string");
s1 = sc.nextLine ();
System.out.println ("enter second string");
s2 = sc.nextLine ();
String a = s1.substring (0, 1);
String b = s1.substring (1, s1.length ());
b=b.toLowerCase();
a = a.toUpperCase();
s1 = a+b;
System.out.println ("The Final String is");
System.out.print (s1+" ");
System.out.println (s2.toUpperCase());
}
}
| UTF-8 | Java | 571 | java | String(Activity1).java | Java | []
| null | []
| import java.util.*;
public class Main
{
public static void main (String[]args)
{
String s1, s2;
Scanner sc = new Scanner (System.in);
System.out.println ("enter first string");
s1 = sc.nextLine ();
System.out.println ("enter second string");
s2 = sc.nextLine ();
String a = s1.substring (0, 1);
String b = s1.substring (1, s1.length ());
b=b.toLowerCase();
a = a.toUpperCase();
s1 = a+b;
System.out.println ("The Final String is");
System.out.print (s1+" ");
System.out.println (s2.toUpperCase());
}
}
| 571 | 0.593695 | 0.570928 | 23 | 23.826086 | 16.377748 | 47 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.782609 | false | false | 13 |
fc33665e810ef68163e83be6341ff4f419723759 | 12,017,318,522,745 | 70b78ae2676836794fa6a3a8cf9c15a7b67f33f7 | /src/cn/edu/henu/subject2/Solution2.java | 7971f4e5010277822a250caf56ad568347fd162d | []
| no_license | StephenChen9527/SwordForOffer | https://github.com/StephenChen9527/SwordForOffer | 69b5ea6e7dfcf7c98758ff5c9dafa2366ee00e2a | dad7f32f72b335d4fc23bbc506b07cad14a85dcb | refs/heads/master | 2021-08-17T00:52:42.800000 | 2017-11-20T15:53:03 | 2017-11-20T15:53:03 | 111,210,995 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn.edu.henu.subject2;
/**
* 请实现一个函数,将一个字符串中的空格替换成“%20”。
* 例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
* ps:普通做法
* @author StephenChen9527
*
*/
public class Solution2 {
public String replaceSpace(StringBuffer str) {
char[] chars=str.toString().toCharArray();
StringBuilder sb=new StringBuilder();
for (char c : chars) {
if(c==' '){
sb.append("%20");
}else{
sb.append(c);
}
}
return sb.toString();
}
} | UTF-8 | Java | 586 | java | Solution2.java | Java | [
{
"context": "替换之后的字符串为We%20Are%20Happy。\r\n * ps:普通做法\r\n * @author StephenChen9527\r\n *\r\n */\r\npublic class Solution2 {\r\n public St",
"end": 161,
"score": 0.9866064190864563,
"start": 146,
"tag": "USERNAME",
"value": "StephenChen9527"
}
]
| null | []
| package cn.edu.henu.subject2;
/**
* 请实现一个函数,将一个字符串中的空格替换成“%20”。
* 例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
* ps:普通做法
* @author StephenChen9527
*
*/
public class Solution2 {
public String replaceSpace(StringBuffer str) {
char[] chars=str.toString().toCharArray();
StringBuilder sb=new StringBuilder();
for (char c : chars) {
if(c==' '){
sb.append("%20");
}else{
sb.append(c);
}
}
return sb.toString();
}
} | 586 | 0.598361 | 0.569672 | 22 | 20.272728 | 16.262568 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.318182 | false | false | 13 |
1e909986939214e8da3c564b6e03c25366d9e4e0 | 22,024,592,351,652 | d561f8576629d4620493384aa3832df15bae878c | /src/day26inheritanceoverriding/Bird.java | 642943725929d5fc213e6f1e4b2071886f4109ee | []
| no_license | MrsCenik/learningCoreJava | https://github.com/MrsCenik/learningCoreJava | ccba642caa59f580d027817c84d19166518c2c0e | 52009f046a71b0335de90a325442a1aa9a822ea4 | refs/heads/main | 2023-08-17T16:44:13.017000 | 2021-09-27T05:04:51 | 2021-09-27T05:04:51 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package day26inheritanceoverriding;
/*
super()
1) super() is used to call a specific constructor from parent class
2) Typing "super()" or not typing "super()" have same meaning
3) super() must be used in the first line inside the constructor
4) super can be used just once inside the constructor
*/
public class Bird extends Mammal{
String name="Bird";
int height=11;
byte ageOfBird=1;
public Bird() {
//super(3);
System.out.println(super.ageOfAnimal);
System.out.println(super.ageOfMammal);
System.out.println(super.height);
System.out.println(super.name);
super.move(); //Mammals move..
System.out.println("Child constructor ran...");
}
public void move() {
System.out.println("Birds move..");
}
public void fly() {
System.out.println("Birds fly..");
}
}
| UTF-8 | Java | 810 | java | Bird.java | Java | [
{
"context": "/\npublic class Bird extends Mammal{\n\tString name=\"Bird\";\n\tint height=11;\n\tbyte ageOfBird=1;\n\n\tpublic Bir",
"end": 364,
"score": 0.9981603622436523,
"start": 360,
"tag": "NAME",
"value": "Bird"
}
]
| null | []
| package day26inheritanceoverriding;
/*
super()
1) super() is used to call a specific constructor from parent class
2) Typing "super()" or not typing "super()" have same meaning
3) super() must be used in the first line inside the constructor
4) super can be used just once inside the constructor
*/
public class Bird extends Mammal{
String name="Bird";
int height=11;
byte ageOfBird=1;
public Bird() {
//super(3);
System.out.println(super.ageOfAnimal);
System.out.println(super.ageOfMammal);
System.out.println(super.height);
System.out.println(super.name);
super.move(); //Mammals move..
System.out.println("Child constructor ran...");
}
public void move() {
System.out.println("Birds move..");
}
public void fly() {
System.out.println("Birds fly..");
}
}
| 810 | 0.687654 | 0.675309 | 33 | 23.545454 | 20.729267 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.666667 | false | false | 13 |
29fb1b70febb2ea434abd5724f2352bf0713a540 | 2,302,102,528,506 | 8a96ef96d0ce94cef125db544f871fd6f2672591 | /library/src/main/java/com/itude/mobile/mobbl/core/view/builders/MBContentViewWrapper.java | f4db84b7970e028cd3bad30485a1e26304923c94 | [
"Apache-2.0"
]
| permissive | sven-m/itude-mobile-android-mobbl | https://github.com/sven-m/itude-mobile-android-mobbl | 25a8ea4ce58834651efc3f69fb22c98794bd5d04 | 448734cfd3c8ff8c448c00472992fe8d82d95f0f | refs/heads/master | 2021-01-18T02:54:30.738000 | 2015-04-28T09:39:03 | 2015-04-28T09:39:03 | 20,856,197 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.itude.mobile.mobbl.core.view.builders;
import android.view.View;
import com.itude.mobile.mobbl.core.controller.MBViewManager;
public interface MBContentViewWrapper {
public View buildContentView(MBViewManager viewManager, View mainContainer);
}
| UTF-8 | Java | 264 | java | MBContentViewWrapper.java | Java | []
| null | []
| package com.itude.mobile.mobbl.core.view.builders;
import android.view.View;
import com.itude.mobile.mobbl.core.controller.MBViewManager;
public interface MBContentViewWrapper {
public View buildContentView(MBViewManager viewManager, View mainContainer);
}
| 264 | 0.82197 | 0.82197 | 9 | 28.333334 | 28.71701 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.555556 | false | false | 13 |
cb4946b26e1bbe040c553845e7a493ec3dc10fcd | 2,302,102,531,427 | 30785a635e4bbbdc0d29d55b547cf938b63625d0 | /iam-login-service/src/test/java/it/infn/mw/iam/test/oauth/UserInfoEndpointTests.java | c8b9abc4657179d24011e48929b5613f6565704a | [
"Apache-2.0"
]
| permissive | praveenmunagapati/iam-1 | https://github.com/praveenmunagapati/iam-1 | 0ebdbf73a7fd3d48f75d0716a337e3c6c5e2a9cb | b06d4d2c7acf206ece7cb0bc9059f56c03d65fc0 | refs/heads/master | 2021-08-31T07:44:20.646000 | 2017-09-29T16:39:58 | 2017-09-29T16:39:58 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package it.infn.mw.iam.test.oauth;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import javax.transaction.Transactional;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import it.infn.mw.iam.IamLoginService;
import it.infn.mw.iam.test.core.CoreControllerTestSupport;
import it.infn.mw.iam.test.util.WithMockOAuthUser;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {IamLoginService.class, CoreControllerTestSupport.class})
@WebAppConfiguration
@Transactional
public class UserInfoEndpointTests {
@Autowired
private WebApplicationContext context;
private MockMvc mvc;
@Before
public void setup() throws Exception {
mvc = MockMvcBuilders.webAppContextSetup(context)
.apply(springSecurity())
.alwaysDo(print())
.build();
}
@Test
@WithMockOAuthUser(clientId = "client-cred", scopes = {"openid"})
public void testUserInfoEndpointReturs404ForClientCredentialsToken() throws Exception {
// @formatter:off
mvc.perform(get("/userinfo"))
.andExpect(status().isForbidden());
// @formatter:on
}
@Test
@WithMockOAuthUser(clientId = "password-grant", user = "test", authorities = {"ROLE_USER"},
scopes = {"openid"})
public void testUserInfoEndpointRetursOk() throws Exception {
// @formatter:off
mvc.perform(get("/userinfo"))
.andExpect(status().isOk());
// @formatter:on
}
}
| UTF-8 | Java | 2,209 | java | UserInfoEndpointTests.java | Java | []
| null | []
| package it.infn.mw.iam.test.oauth;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import javax.transaction.Transactional;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import it.infn.mw.iam.IamLoginService;
import it.infn.mw.iam.test.core.CoreControllerTestSupport;
import it.infn.mw.iam.test.util.WithMockOAuthUser;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {IamLoginService.class, CoreControllerTestSupport.class})
@WebAppConfiguration
@Transactional
public class UserInfoEndpointTests {
@Autowired
private WebApplicationContext context;
private MockMvc mvc;
@Before
public void setup() throws Exception {
mvc = MockMvcBuilders.webAppContextSetup(context)
.apply(springSecurity())
.alwaysDo(print())
.build();
}
@Test
@WithMockOAuthUser(clientId = "client-cred", scopes = {"openid"})
public void testUserInfoEndpointReturs404ForClientCredentialsToken() throws Exception {
// @formatter:off
mvc.perform(get("/userinfo"))
.andExpect(status().isForbidden());
// @formatter:on
}
@Test
@WithMockOAuthUser(clientId = "password-grant", user = "test", authorities = {"ROLE_USER"},
scopes = {"openid"})
public void testUserInfoEndpointRetursOk() throws Exception {
// @formatter:off
mvc.perform(get("/userinfo"))
.andExpect(status().isOk());
// @formatter:on
}
}
| 2,209 | 0.784518 | 0.781802 | 63 | 34.063492 | 29.691467 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.460317 | false | false | 13 |
defe9ced0bfbb3e28d36fe3316594eceb92db195 | 22,101,901,761,414 | aae9b73c389f9344f8e2803753d94c46d37d0e9e | /src/day10forloops/ForLoop01.java | 0fe7c55b4f984f4a8d08bf000df26a42914a9419 | []
| no_license | cemalsenel/coreJavaNotes | https://github.com/cemalsenel/coreJavaNotes | 840319569725efbc88ea20bd7d0d5d5ea0764397 | 697b142db356cc593ba24110534e2e421e39a6e2 | refs/heads/main | 2023-06-24T15:19:36.202000 | 2021-07-19T18:35:30 | 2021-07-19T18:35:30 | 387,560,482 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package day10forloops;
import java.util.Scanner;
public class ForLoop01 {
public static void main(String[] args) {
// printEvenInt1();
// printEventInt2();
//printDivByFive();
printInRevOrder();
}
/*
* Print all even integers from 100 to 23 on the console in the same line wit a
* space among them
*/
public static void printEvenInt1() {
for (int i = 100; i > 22; i -= 2) {
System.out.print(i + " ");
}
}
public static void printEventInt2() {
for (int i = 100; i > 22; i--) {
if (i % 2 == 0) {
System.out.print(i + " ");
}
}
}
public static void printDivByFive() {
/*
* Print all integers which are divisible by 5 from 100 to 23 on the console
*/
for (int i = 100; i > 22; i--) {
if (i % 5 == 0) {
System.out.print(i + " ");
}
}
}
public static void printInRevOrder() {
/*
* Interview Question 1)Ask user to enter a String 2)Print the String reverse
* For example; Germany ===> ynamreG
*/
Scanner scan = new Scanner(System.in);
System.out.println("Enter a String to see it in reverse order");
String str = scan.nextLine();
scan.close();
for(int i = str.length()-1 ;i>=0 ; i-- ) {
System.out.print(str.charAt(i));
}
}
}
| UTF-8 | Java | 1,234 | java | ForLoop01.java | Java | []
| null | []
| package day10forloops;
import java.util.Scanner;
public class ForLoop01 {
public static void main(String[] args) {
// printEvenInt1();
// printEventInt2();
//printDivByFive();
printInRevOrder();
}
/*
* Print all even integers from 100 to 23 on the console in the same line wit a
* space among them
*/
public static void printEvenInt1() {
for (int i = 100; i > 22; i -= 2) {
System.out.print(i + " ");
}
}
public static void printEventInt2() {
for (int i = 100; i > 22; i--) {
if (i % 2 == 0) {
System.out.print(i + " ");
}
}
}
public static void printDivByFive() {
/*
* Print all integers which are divisible by 5 from 100 to 23 on the console
*/
for (int i = 100; i > 22; i--) {
if (i % 5 == 0) {
System.out.print(i + " ");
}
}
}
public static void printInRevOrder() {
/*
* Interview Question 1)Ask user to enter a String 2)Print the String reverse
* For example; Germany ===> ynamreG
*/
Scanner scan = new Scanner(System.in);
System.out.println("Enter a String to see it in reverse order");
String str = scan.nextLine();
scan.close();
for(int i = str.length()-1 ;i>=0 ; i-- ) {
System.out.print(str.charAt(i));
}
}
}
| 1,234 | 0.595624 | 0.560778 | 63 | 18.587301 | 20.944853 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.809524 | false | false | 13 |
657d168449bd49b7eea255a416aecbffb99456dd | 738,734,433,191 | 8bbf8b55e074bdaa0398ceee8cf5ad8337d046ba | /src/view/tools/SalvarComo.java | cfcfc0739c66119214e9efd81464125a9792007c | []
| no_license | RPGMBR/RPGmanager-src | https://github.com/RPGMBR/RPGmanager-src | af3fcffc4d5f847f04d63265794a1c67bcab7f99 | f974067b25c540be34625d5460340e2b317abf4a | refs/heads/master | 2018-04-13T11:51:19.293000 | 2012-12-01T19:57:57 | 2012-12-01T19:57:57 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package view.tools;
import entity.dt3e.Personagem3dt;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;
/**
*
* @author RodrigoAL
*/
public class SalvarComo extends javax.swing.JDialog {
private Personagem3dt pj;
/**
* Creates new form SalvarComo
*/
public SalvarComo(java.awt.Frame parent, Personagem3dt pj) {
super(parent, true);
this.pj = pj;
initComponents();
FileChooser.setFileFilter(new FileNameExtensionFilter("Arquivo de texto", "txt"));
// FileChooser.setFileFilter(new FileNameExtensionFilter("pdf", "pdf"));
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
FileChooser = new javax.swing.JFileChooser();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Salvar...");
FileChooser.setDialogType(javax.swing.JFileChooser.SAVE_DIALOG);
FileChooser.setCurrentDirectory(null);
FileChooser.setDialogTitle("Salvar");
FileChooser.setFont(new java.awt.Font("Trebuchet MS", 0, 12)); // NOI18N
FileChooser.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
FileChooserActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(FileChooser, javax.swing.GroupLayout.DEFAULT_SIZE, 600, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(FileChooser, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void FileChooserActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_FileChooserActionPerformed
if (evt.paramString().contains("ApproveSelection")) {
//String text= pj.toText();
}
}//GEN-LAST:event_FileChooserActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JFileChooser FileChooser;
// End of variables declaration//GEN-END:variables
}
| UTF-8 | Java | 2,892 | java | SalvarComo.java | Java | [
{
"context": "hooser.FileNameExtensionFilter;\n\n/**\n *\n * @author RodrigoAL\n */\npublic class SalvarComo extends javax.swing.J",
"end": 271,
"score": 0.990946888923645,
"start": 262,
"tag": "NAME",
"value": "RodrigoAL"
}
]
| null | []
| /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package view.tools;
import entity.dt3e.Personagem3dt;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;
/**
*
* @author RodrigoAL
*/
public class SalvarComo extends javax.swing.JDialog {
private Personagem3dt pj;
/**
* Creates new form SalvarComo
*/
public SalvarComo(java.awt.Frame parent, Personagem3dt pj) {
super(parent, true);
this.pj = pj;
initComponents();
FileChooser.setFileFilter(new FileNameExtensionFilter("Arquivo de texto", "txt"));
// FileChooser.setFileFilter(new FileNameExtensionFilter("pdf", "pdf"));
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
FileChooser = new javax.swing.JFileChooser();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Salvar...");
FileChooser.setDialogType(javax.swing.JFileChooser.SAVE_DIALOG);
FileChooser.setCurrentDirectory(null);
FileChooser.setDialogTitle("Salvar");
FileChooser.setFont(new java.awt.Font("Trebuchet MS", 0, 12)); // NOI18N
FileChooser.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
FileChooserActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(FileChooser, javax.swing.GroupLayout.DEFAULT_SIZE, 600, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(FileChooser, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void FileChooserActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_FileChooserActionPerformed
if (evt.paramString().contains("ApproveSelection")) {
//String text= pj.toText();
}
}//GEN-LAST:event_FileChooserActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JFileChooser FileChooser;
// End of variables declaration//GEN-END:variables
}
| 2,892 | 0.687068 | 0.682918 | 76 | 37.052631 | 32.664925 | 131 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.526316 | false | false | 13 |
1573aaad0713409890f78cc64709bf45fed4359d | 309,237,707,181 | ee373460453fadfde3012dd79dda008774029ac5 | /app/src/main/java/cn/paulpaulzhang/dormitorymanagement/model/Building.java | 0d1f643aec8632ffd91d0bd542c7a9eec9dd5754 | []
| no_license | paulpaulzhang/DormitoryManagement | https://github.com/paulpaulzhang/DormitoryManagement | a1be0c302843e6ea6669c9e3da7f5c75fe686058 | 73db09b633e3c7b1b0da8c3442e5c72f6d35b5a9 | refs/heads/master | 2020-07-10T06:05:48.856000 | 2019-09-29T07:13:20 | 2019-09-29T07:13:20 | 204,186,637 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn.paulpaulzhang.dormitorymanagement.model;
import io.objectbox.annotation.Entity;
import io.objectbox.annotation.Id;
/**
* 包名: cn.paulpaulzhang.dormitorymanagement.database.model
* 创建时间: 8/3/2019
* 创建人: zlm31
* 描述:
*/
@Entity
public class Building {
@Id
private long id;
private String name;
private String introduction;
public Building(String name, String introduction) {
this.name = name;
this.introduction = introduction;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIntroduction() {
return introduction;
}
public void setIntroduction(String introduction) {
this.introduction = introduction;
}
}
| UTF-8 | Java | 932 | java | Building.java | Java | [
{
"context": "anagement.database.model\n * 创建时间: 8/3/2019\n * 创建人: zlm31\n * 描述:\n */\n@Entity\npublic class Building {\n @I",
"end": 222,
"score": 0.999565839767456,
"start": 217,
"tag": "USERNAME",
"value": "zlm31"
}
]
| null | []
| package cn.paulpaulzhang.dormitorymanagement.model;
import io.objectbox.annotation.Entity;
import io.objectbox.annotation.Id;
/**
* 包名: cn.paulpaulzhang.dormitorymanagement.database.model
* 创建时间: 8/3/2019
* 创建人: zlm31
* 描述:
*/
@Entity
public class Building {
@Id
private long id;
private String name;
private String introduction;
public Building(String name, String introduction) {
this.name = name;
this.introduction = introduction;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIntroduction() {
return introduction;
}
public void setIntroduction(String introduction) {
this.introduction = introduction;
}
}
| 932 | 0.634066 | 0.625275 | 49 | 17.571428 | 17.235464 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.306122 | false | false | 13 |
3a7c178b48480b694f4c5d0b86d3e3db72c617d0 | 25,400,436,636,910 | c07b7bed9e7e7204a14c77e878388b7a165be64c | /app/src/main/java/com/ndanh/mytranslator/screen/help/HelpActivity.java | 84c22cea9cc930f0068c80ac494c84a2246f826f | []
| no_license | pnlinh-it/MyTranslator | https://github.com/pnlinh-it/MyTranslator | 04b0f4b788bc69199bed9761d88f69067f8caf15 | 8a7de4221684c86f412d75c39c7a167bc0f11428 | refs/heads/master | 2020-03-21T19:57:26.436000 | 2017-11-23T03:34:05 | 2017-11-23T03:34:05 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ndanh.mytranslator.screen.help;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import com.ndanh.mytranslator.R;
import com.ndanh.mytranslator.base.BaseActivity;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class HelpActivity extends BaseActivity {
@BindView( R.id.webview )
WebView webView;
@Override
protected void initView() {
setContentView ( R.layout.activity_help );
ButterKnife.bind ( this );
webView.loadUrl ( "file:///android_asset/html/help.html" );
}
@OnClick(R.id.action_back)
public void back(View v){
finish ();
}
public static void start(Context context, int... flags) {
Intent starter = new Intent(context, HelpActivity.class);
for ( int flag : flags ) {
starter.addFlags ( flag );
}
context.startActivity(starter);
}
}
| UTF-8 | Java | 1,066 | java | HelpActivity.java | Java | []
| null | []
| package com.ndanh.mytranslator.screen.help;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import com.ndanh.mytranslator.R;
import com.ndanh.mytranslator.base.BaseActivity;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class HelpActivity extends BaseActivity {
@BindView( R.id.webview )
WebView webView;
@Override
protected void initView() {
setContentView ( R.layout.activity_help );
ButterKnife.bind ( this );
webView.loadUrl ( "file:///android_asset/html/help.html" );
}
@OnClick(R.id.action_back)
public void back(View v){
finish ();
}
public static void start(Context context, int... flags) {
Intent starter = new Intent(context, HelpActivity.class);
for ( int flag : flags ) {
starter.addFlags ( flag );
}
context.startActivity(starter);
}
}
| 1,066 | 0.692308 | 0.69137 | 40 | 25.65 | 18.986244 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.55 | false | false | 13 |
b47884e71804afd54e38bd949b3e544d2460b637 | 15,607,911,159,410 | 9704405db138845f84cd71ed928cc428189482ae | /app/src/main/java/com/heyheyda/tradeagent/data/EmptyRealTimeStockInfo.java | 4473b751b255f81ca5af0b8b067d5f1fc5984a87 | [
"Apache-2.0"
]
| permissive | heytsai/tradeAgent | https://github.com/heytsai/tradeAgent | 0d6013c82c04d600f45d1cacc70d0fbc8055b38f | 45fd77835375924b4728d7eb7b03317854c8be8d | refs/heads/master | 2020-04-10T09:57:25.160000 | 2019-04-20T22:57:32 | 2019-04-20T22:57:32 | 160,951,837 | 4 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.heyheyda.tradeagent.data;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import java.util.Date;
import java.util.TimeZone;
public class EmptyRealTimeStockInfo implements RealTimeStockInfo {
private String symbol;
public EmptyRealTimeStockInfo(@NonNull String symbol) {
this.symbol = symbol;
}
@Nullable
@Override
public String getName() {
return null;
}
@Nullable
@Override
public String getSymbol() {
return symbol;
}
@Override
public double getOpen() {
return 0;
}
@Override
public double getHigh() {
return 0;
}
@Override
public double getLow() {
return 0;
}
@Override
public double getPrice() {
return 0;
}
@Override
public double getChange() {
return 0;
}
@Override
public double getChangePercent() {
return 0;
}
@Override
public long getVol() {
return 0;
}
@Nullable
@Override
public Date getTime() {
return null;
}
@Nullable
@Override
public TimeZone getTimeZone() {
return null;
}
}
| UTF-8 | Java | 1,215 | java | EmptyRealTimeStockInfo.java | Java | []
| null | []
| package com.heyheyda.tradeagent.data;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import java.util.Date;
import java.util.TimeZone;
public class EmptyRealTimeStockInfo implements RealTimeStockInfo {
private String symbol;
public EmptyRealTimeStockInfo(@NonNull String symbol) {
this.symbol = symbol;
}
@Nullable
@Override
public String getName() {
return null;
}
@Nullable
@Override
public String getSymbol() {
return symbol;
}
@Override
public double getOpen() {
return 0;
}
@Override
public double getHigh() {
return 0;
}
@Override
public double getLow() {
return 0;
}
@Override
public double getPrice() {
return 0;
}
@Override
public double getChange() {
return 0;
}
@Override
public double getChangePercent() {
return 0;
}
@Override
public long getVol() {
return 0;
}
@Nullable
@Override
public Date getTime() {
return null;
}
@Nullable
@Override
public TimeZone getTimeZone() {
return null;
}
}
| 1,215 | 0.595062 | 0.5893 | 75 | 15.2 | 14.101537 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.24 | false | false | 13 |
b5cc8bfde5da483db4ce57f72cb956950a5fbb19 | 10,539,849,809,132 | 683fd810dd78021a70dbe824c54247f83fed9d38 | /src/fr/mreddy/fruity/sprite/MonstreViolet.java | 191ff99f915048fe51f1aeecaa1dd9191f3bd205 | []
| no_license | Eddy226/FruityFrank | https://github.com/Eddy226/FruityFrank | 00878e6fa5f016d3529bbcc5695b13e4b7598cb6 | e24d02390d5c6b7902831e2134d2ea91a97cca61 | refs/heads/master | 2020-09-07T09:38:05.925000 | 2017-06-20T08:53:04 | 2017-06-20T08:53:04 | 94,424,132 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package fr.mreddy.fruity.sprite;
import fr.mreddy.fruity.*;
public class MonstreViolet extends Sprite
{
public MonstreViolet()
{
super(ManagerMonstres.imgMonstreViolet, null);
}
} | UTF-8 | Java | 189 | java | MonstreViolet.java | Java | []
| null | []
| package fr.mreddy.fruity.sprite;
import fr.mreddy.fruity.*;
public class MonstreViolet extends Sprite
{
public MonstreViolet()
{
super(ManagerMonstres.imgMonstreViolet, null);
}
} | 189 | 0.756614 | 0.756614 | 12 | 14.833333 | 17.396519 | 48 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.833333 | false | false | 13 |
279433bc3729afb9f68f45861bf6623a204a047a | 21,646,635,229,255 | 4edf1fc85343d683b161600c8e1214f4babb7cc9 | /Bookstore/src/java/domain/Bruker.java | 12cac61fd0156a42e51a8444a0cf5eadd51819d8 | []
| no_license | debonatis/SystemeringGruppe11 | https://github.com/debonatis/SystemeringGruppe11 | 14e2817bd18df8fe427925aa9a51b0bbb8d110ef | a0d156ed57f0b6f59a4a08d2e84e94f2e6ba3273 | refs/heads/master | 2021-01-10T11:56:01.757000 | 2013-03-13T16:38:35 | 2013-03-13T16:38:35 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package domain;
import extra.UsrPswWaplj;
import javax.persistence.Id;
/**
*
* @author deb
*/
public class Bruker {
private @Id
@UsrPswWaplj(passordsjekk = 0, message = "This username is already in use,"
+ " or it is one that is too similar.\n "
+ "Write a new one! "
+ "The username must have a lenght between 6 and 10 characters!", sjekkDB = 1)
String brukernavn;
private String rolle;
private @UsrPswWaplj(passordsjekk = 1, message = "The password must contain at least one uppercase "
+ "and one lowercase letter and one number. \n The password must also contain one of following special characters(@#$%&). "
+ "Password must be between 6-10 characters!")
String passord;
String fornavn;
String etternavn;
int postNr;
String gateAdresse;
String postSted;
String email;
int telefon;
private boolean endret;
public synchronized boolean isEndret() {
return endret;
}
public synchronized void setEndret(boolean endret) {
this.endret = endret;
}
public Bruker() {
this.brukernavn = "";
this.rolle = "";
this.passord = "";
this.fornavn = "";
this.etternavn = "";
this.postNr = 0;
this.gateAdresse = "";
this.postSted = "";
this.email = "";
this.telefon = 0;
}
public Bruker(String brukernavn, String passord, String fornavn, String etternavn, int postNr,
String adresse,String postSted,String email, int telefon, String rolle, int i) {
this.brukernavn = brukernavn;
this.passord = passord;
this.fornavn = fornavn;
this.etternavn = etternavn;
this.postNr = postNr;
this.gateAdresse = adresse;
this.postSted = postSted;
this.email = email;
this.telefon = telefon;
this.rolle = rolle;
endret = false;
}
public Bruker(String brukernavn, String passord, String rolle) {
this.brukernavn = brukernavn;
this.rolle = rolle;
this.passord = passord;
endret = false;
}
/**
* Get the value of rolle
*
* @return the value of rolle
*/
public synchronized String getRolle() {
return rolle;
}
/**
* Set the value of rolle
*
* @param rolle new value of rolle
*/
public synchronized void setRolle(String rolle) {
if (!(this.rolle.equalsIgnoreCase(rolle))) {
this.rolle = rolle;
setEndret(true);
}
}
/**
* Get the value of passord
*
* @return the value of passord
*/
public synchronized String getPassord() {
return passord;
}
/**
* Set the value of passord
*
* @param passord new value of passord
*/
public synchronized void setPassord(String passord) {
if (!(this.passord.equalsIgnoreCase(passord))) {
this.passord = passord;
setEndret(true);
}
}
/**
* Get the value of name
*
* @return the value of name
*/
public synchronized String getBrukernavn() {
return brukernavn;
}
/**
* Set the value of name
*
* @param name new value of name
*/
public synchronized void setBrukernavn(String brukernavn) {
if (!(this.brukernavn.equalsIgnoreCase(brukernavn))) {
this.brukernavn = brukernavn;
setEndret(true);
}
}
public String getFornavn() {
return fornavn;
}
public void setFornavn(String fornavn) {
if (!(this.fornavn.equalsIgnoreCase(fornavn))) {
this.fornavn = fornavn;
setEndret(true);
}
}
public String getEtternavn() {
return etternavn;
}
public void setEtternavn(String etternavn) {
if (!(this.etternavn.equalsIgnoreCase(etternavn))) {
this.etternavn = etternavn;
setEndret(true);
}
}
public int getPostNr() {
return postNr;
}
public void setPostNr(int postNr) {
if (!(this.postNr == postNr)) {
this.postNr = postNr;
setEndret(true);
}
}
public String getGateAdresse() {
return gateAdresse;
}
public void setGateAdresse(String gateAdresse) {
if (!(this.gateAdresse.equalsIgnoreCase(gateAdresse))) {
this.gateAdresse = gateAdresse;
setEndret(true);
}
}
public String getPostSted() {
return postSted;
}
public void setPostSted(String postSted) {
if (!(this.postSted.equalsIgnoreCase(postSted))) {
this.postSted = postSted;
setEndret(true);
}
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
if (!(this.email.equalsIgnoreCase(email))) {
this.email = email;
setEndret(true);
}
}
public int getTelefon() {
return telefon;
}
public void setTelefon(int telefon) {
if (!(this.telefon == telefon)) {
this.telefon = telefon;
setEndret(true);
}
}
}
| UTF-8 | Java | 5,536 | java | Bruker.java | Java | [
{
"context": "mport javax.persistence.Id;\r\n\r\n/**\r\n *\r\n * @author deb\r\n */\r\npublic class Bruker {\r\n private @Id\r\n ",
"end": 205,
"score": 0.9975492358207703,
"start": 202,
"tag": "USERNAME",
"value": "deb"
},
{
"context": "s.brukernavn = brukernavn;\r\n this.passord = passord;\r\n this.fornavn = fornavn;\r\n thi",
"end": 1780,
"score": 0.8476793169975281,
"start": 1776,
"tag": "PASSWORD",
"value": "pass"
}
]
| null | []
| /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package domain;
import extra.UsrPswWaplj;
import javax.persistence.Id;
/**
*
* @author deb
*/
public class Bruker {
private @Id
@UsrPswWaplj(passordsjekk = 0, message = "This username is already in use,"
+ " or it is one that is too similar.\n "
+ "Write a new one! "
+ "The username must have a lenght between 6 and 10 characters!", sjekkDB = 1)
String brukernavn;
private String rolle;
private @UsrPswWaplj(passordsjekk = 1, message = "The password must contain at least one uppercase "
+ "and one lowercase letter and one number. \n The password must also contain one of following special characters(@#$%&). "
+ "Password must be between 6-10 characters!")
String passord;
String fornavn;
String etternavn;
int postNr;
String gateAdresse;
String postSted;
String email;
int telefon;
private boolean endret;
public synchronized boolean isEndret() {
return endret;
}
public synchronized void setEndret(boolean endret) {
this.endret = endret;
}
public Bruker() {
this.brukernavn = "";
this.rolle = "";
this.passord = "";
this.fornavn = "";
this.etternavn = "";
this.postNr = 0;
this.gateAdresse = "";
this.postSted = "";
this.email = "";
this.telefon = 0;
}
public Bruker(String brukernavn, String passord, String fornavn, String etternavn, int postNr,
String adresse,String postSted,String email, int telefon, String rolle, int i) {
this.brukernavn = brukernavn;
this.passord = <PASSWORD>ord;
this.fornavn = fornavn;
this.etternavn = etternavn;
this.postNr = postNr;
this.gateAdresse = adresse;
this.postSted = postSted;
this.email = email;
this.telefon = telefon;
this.rolle = rolle;
endret = false;
}
public Bruker(String brukernavn, String passord, String rolle) {
this.brukernavn = brukernavn;
this.rolle = rolle;
this.passord = passord;
endret = false;
}
/**
* Get the value of rolle
*
* @return the value of rolle
*/
public synchronized String getRolle() {
return rolle;
}
/**
* Set the value of rolle
*
* @param rolle new value of rolle
*/
public synchronized void setRolle(String rolle) {
if (!(this.rolle.equalsIgnoreCase(rolle))) {
this.rolle = rolle;
setEndret(true);
}
}
/**
* Get the value of passord
*
* @return the value of passord
*/
public synchronized String getPassord() {
return passord;
}
/**
* Set the value of passord
*
* @param passord new value of passord
*/
public synchronized void setPassord(String passord) {
if (!(this.passord.equalsIgnoreCase(passord))) {
this.passord = passord;
setEndret(true);
}
}
/**
* Get the value of name
*
* @return the value of name
*/
public synchronized String getBrukernavn() {
return brukernavn;
}
/**
* Set the value of name
*
* @param name new value of name
*/
public synchronized void setBrukernavn(String brukernavn) {
if (!(this.brukernavn.equalsIgnoreCase(brukernavn))) {
this.brukernavn = brukernavn;
setEndret(true);
}
}
public String getFornavn() {
return fornavn;
}
public void setFornavn(String fornavn) {
if (!(this.fornavn.equalsIgnoreCase(fornavn))) {
this.fornavn = fornavn;
setEndret(true);
}
}
public String getEtternavn() {
return etternavn;
}
public void setEtternavn(String etternavn) {
if (!(this.etternavn.equalsIgnoreCase(etternavn))) {
this.etternavn = etternavn;
setEndret(true);
}
}
public int getPostNr() {
return postNr;
}
public void setPostNr(int postNr) {
if (!(this.postNr == postNr)) {
this.postNr = postNr;
setEndret(true);
}
}
public String getGateAdresse() {
return gateAdresse;
}
public void setGateAdresse(String gateAdresse) {
if (!(this.gateAdresse.equalsIgnoreCase(gateAdresse))) {
this.gateAdresse = gateAdresse;
setEndret(true);
}
}
public String getPostSted() {
return postSted;
}
public void setPostSted(String postSted) {
if (!(this.postSted.equalsIgnoreCase(postSted))) {
this.postSted = postSted;
setEndret(true);
}
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
if (!(this.email.equalsIgnoreCase(email))) {
this.email = email;
setEndret(true);
}
}
public int getTelefon() {
return telefon;
}
public void setTelefon(int telefon) {
if (!(this.telefon == telefon)) {
this.telefon = telefon;
setEndret(true);
}
}
}
| 5,542 | 0.54823 | 0.546243 | 217 | 23.51152 | 21.091442 | 128 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.410138 | false | false | 13 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.