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
0cf9787678d491118c69e4eb8ffdd9dc85224549
18,906,446,047,258
c3618029de64c7eb80f2572a8a093b4140fa9942
/src/main/java/com/example/account/service/impl/SysUserServiceImpl.java
6e35787926af741b33e31852ba0d4d09470f6b79
[]
no_license
VxiaomageV/account
https://github.com/VxiaomageV/account
9ccc80bf724b938d1352e7aa3ffb8a6cea5b2689
b5701512df5923615ad9f46241f544a4612feff5
refs/heads/master
2020-09-14T08:43:26.131000
2019-11-21T06:18:08
2019-11-21T06:18:08
223,071,265
0
0
null
false
2019-11-21T02:50:50
2019-11-21T02:32:11
2019-11-21T02:32:14
2019-11-21T02:50:49
0
0
0
0
null
false
false
package com.example.account.service.impl; import com.example.account.dao.SysUserMapper; import com.example.account.po.SysUser; import com.example.account.service.SysUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; /** * @description: * @author: mal * @date: 2019/10/24 */ @Service @Transactional(rollbackFor = Exception.class) public class SysUserServiceImpl implements SysUserService { @Autowired SysUserMapper sysUserMapper; /** * description: 根据id查询用户 * creat: mal * date: 2019/10/22 */ @Override public SysUser selectById(int id) { return sysUserMapper.selectByPrimaryKey(id); } /** * description: 事务demo 读写提交 新建事务 * creat: mal * date: 2019/10/28 * */ @Override @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class) public void insertSysUser() { SysUser sysUser = new SysUser(); sysUser.setCode("wle"); sysUser.setName("吴老二"); sysUserMapper.insertSelective(sysUser); } }
UTF-8
Java
1,387
java
SysUserServiceImpl.java
Java
[ { "context": "n.Transactional;\n\n/**\n * @description:\n * @author: mal\n * @date: 2019/10/24\n */\n@Service\n@Transactional(", "end": 515, "score": 0.5055140852928162, "start": 512, "tag": "NAME", "value": "mal" }, { "context": " /**\n * description: 根据id查询用户\n * creat: ...
null
[]
package com.example.account.service.impl; import com.example.account.dao.SysUserMapper; import com.example.account.po.SysUser; import com.example.account.service.SysUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; /** * @description: * @author: mal * @date: 2019/10/24 */ @Service @Transactional(rollbackFor = Exception.class) public class SysUserServiceImpl implements SysUserService { @Autowired SysUserMapper sysUserMapper; /** * description: 根据id查询用户 * creat: mal * date: 2019/10/22 */ @Override public SysUser selectById(int id) { return sysUserMapper.selectByPrimaryKey(id); } /** * description: 事务demo 读写提交 新建事务 * creat: mal * date: 2019/10/28 * */ @Override @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class) public void insertSysUser() { SysUser sysUser = new SysUser(); sysUser.setCode("wle"); sysUser.setName("吴老二"); sysUserMapper.insertSelective(sysUser); } }
1,387
0.714603
0.696812
51
25.450981
24.779272
127
false
false
0
0
0
0
0
0
0.333333
false
false
13
56313141b31653f8c00c421d530a6c1e37911890
15,908,558,871,809
c56c82cbba2fffccd840cf57dd988b87f87186ea
/base_module/mvvmwill/src/main/java/com/will/habit/widget/dialog/leak/LeakSafeBottomDialog.java
79f7bb7d277296cb9c749e5277164ee90162faa7
[ "Apache-2.0" ]
permissive
willpyshan13/DouYinPlay
https://github.com/willpyshan13/DouYinPlay
7e97b6d92ad56a02d57aca61939604da6b7f9cc1
4c4cd66f9fb9c32843767a29e113758384be395a
refs/heads/master
2023-06-22T00:28:24.218000
2021-07-24T00:20:32
2021-07-24T00:20:32
273,811,029
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.will.habit.widget.dialog.leak; import android.content.Context; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.google.android.material.bottomsheet.BottomSheetDialog; /** * Desc: 解决dialog泄漏问题 * dialog的listener是用handler发送的,导致dialog被持有无法释放 * 解决:包装一层listener,使用WeakReference持有 * <p> * Date: 2019-07-22 * Copyright: Copyright (c) 2010-2019 * Updater: * Update Time: 2019/9/3 * Update Comments: * * @Author: pengyushan */ public class LeakSafeBottomDialog extends BottomSheetDialog { public LeakSafeBottomDialog(@NonNull Context context) { super(context); } public LeakSafeBottomDialog(@NonNull Context context, int themeResId) { super(context, themeResId); } protected LeakSafeBottomDialog(@NonNull Context context, boolean cancelable, @Nullable OnCancelListener cancelListener) { super(context, cancelable, cancelListener); } @Override public void setOnCancelListener(@Nullable OnCancelListener listener) { super.setOnCancelListener(new WrapperSafeOnCancelListener(listener)); } @Override public void setOnShowListener(@Nullable OnShowListener listener) { super.setOnShowListener(new WrapperSafeOnShowListener(listener)); } @Override public void setOnDismissListener(@Nullable OnDismissListener listener) { super.setOnDismissListener(new WrapperSafeOnDismissListener(listener)); } }
UTF-8
Java
1,525
java
LeakSafeBottomDialog.java
Java
[ { "context": " Time: 2019/9/3\n * Update Comments:\n *\n * @Author: pengyushan\n */\npublic class LeakSafeBottomDialog extends Bot", "end": 475, "score": 0.999642014503479, "start": 465, "tag": "USERNAME", "value": "pengyushan" } ]
null
[]
package com.will.habit.widget.dialog.leak; import android.content.Context; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.google.android.material.bottomsheet.BottomSheetDialog; /** * Desc: 解决dialog泄漏问题 * dialog的listener是用handler发送的,导致dialog被持有无法释放 * 解决:包装一层listener,使用WeakReference持有 * <p> * Date: 2019-07-22 * Copyright: Copyright (c) 2010-2019 * Updater: * Update Time: 2019/9/3 * Update Comments: * * @Author: pengyushan */ public class LeakSafeBottomDialog extends BottomSheetDialog { public LeakSafeBottomDialog(@NonNull Context context) { super(context); } public LeakSafeBottomDialog(@NonNull Context context, int themeResId) { super(context, themeResId); } protected LeakSafeBottomDialog(@NonNull Context context, boolean cancelable, @Nullable OnCancelListener cancelListener) { super(context, cancelable, cancelListener); } @Override public void setOnCancelListener(@Nullable OnCancelListener listener) { super.setOnCancelListener(new WrapperSafeOnCancelListener(listener)); } @Override public void setOnShowListener(@Nullable OnShowListener listener) { super.setOnShowListener(new WrapperSafeOnShowListener(listener)); } @Override public void setOnDismissListener(@Nullable OnDismissListener listener) { super.setOnDismissListener(new WrapperSafeOnDismissListener(listener)); } }
1,525
0.748799
0.733699
51
27.568628
29.707235
125
false
false
0
0
0
0
0
0
0.333333
false
false
13
a7a60ac18fd6e8139a90cf425aaca7e1db423b4d
5,059,471,487,187
9f44bc52dfab54d500b0e4a7ca579934bcb67e5e
/exercises_3/Employee.java
4bee71056ee0c26c83b4330f8c330c69f2e51913
[]
no_license
Patrick5455/Java_Data_Structures_Algorithms-Deitel-
https://github.com/Patrick5455/Java_Data_Structures_Algorithms-Deitel-
e3ebf024c7abe7e59a09670f8e35e109641677bd
5a438a33baa7e104b6df18a55cbde313e41ed68e
refs/heads/master
2020-09-23T23:25:04.927000
2020-06-26T20:06:42
2020-06-26T20:06:42
225,613,172
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Algorithm_Solutions.exercises_3; public class Employee{ private String firstName; private String lastName; private double salary; private double salaryRaise; public Employee(String firstName, String lastName, double salary){ this.firstName = firstName; this.lastName = lastName; this.salary = salary; } public void setFirstName (String firstName){ this.firstName = firstName; } public String getFirstName (){ return firstName; } public void setLastName(String lastName){ this.lastName = lastName; } public String getLastName (){ return lastName; } public void setSalary(double salary){ if (salary > 0){ this.salary = salary; } else { System.out.println("Salary is a negative value"); } } public double getSalary(){ return salary; } public double yearlySalary(){ return salary*12; } public void setSalaryRaise(double raise){ salaryRaise = (salary)*(1+(raise/100)); } public double getsalaryRaise(){ return salaryRaise; } public double yearlySalaryRaise(){ return salaryRaise*12; } }
UTF-8
Java
1,204
java
Employee.java
Java
[ { "context": " lastName, double salary){\r\n\t\t\r\n\t\tthis.firstName = firstName;\r\n\t\tthis.lastName = lastName;\r\n\t\tthis.salary = sa", "end": 285, "score": 0.9636949300765991, "start": 276, "tag": "NAME", "value": "firstName" }, { "context": "\r\n\t\tthis.firstName = firstNam...
null
[]
package Algorithm_Solutions.exercises_3; public class Employee{ private String firstName; private String lastName; private double salary; private double salaryRaise; public Employee(String firstName, String lastName, double salary){ this.firstName = firstName; this.lastName = lastName; this.salary = salary; } public void setFirstName (String firstName){ this.firstName = firstName; } public String getFirstName (){ return firstName; } public void setLastName(String lastName){ this.lastName = lastName; } public String getLastName (){ return lastName; } public void setSalary(double salary){ if (salary > 0){ this.salary = salary; } else { System.out.println("Salary is a negative value"); } } public double getSalary(){ return salary; } public double yearlySalary(){ return salary*12; } public void setSalaryRaise(double raise){ salaryRaise = (salary)*(1+(raise/100)); } public double getsalaryRaise(){ return salaryRaise; } public double yearlySalaryRaise(){ return salaryRaise*12; } }
1,204
0.634551
0.626246
78
13.320513
15.801245
67
false
false
0
0
0
0
0
0
1.5
false
false
13
7281424fb55a4259fbd43266525501eb18a54363
31,937,376,815,201
d32b3d2b97b7130613705d8647c825450979401c
/kodilla-good-patterns/src/main/java/com/kodilla/good/patterns/orderTask/Application.java
99bf67309ee1cf83461e3e39ef2d10136e99ccbd
[]
no_license
marcinkostka/marcin-kostka-kodilla-java
https://github.com/marcinkostka/marcin-kostka-kodilla-java
3b22c3fac7a740fb944706b0287314b82269548d
22303aeb58a00232d0a594a8a11ba22b0a116c22
refs/heads/master
2021-09-14T18:50:19.672000
2018-05-17T14:29:24
2018-05-17T14:29:24
115,539,948
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.kodilla.good.patterns.orderTask; public class Application { public static void main(String[] args) { OrderRequestRetriever orderRequestRetriever = new OrderRequestRetriever(); OrderRequest orderRequest = orderRequestRetriever.retrieve(); InformationServiceData informationServiceData = new InformationServiceData(); OrderServiceData orderServiceData = new OrderServiceData(); OrderRepositoryData orderRepositoryData = new OrderRepositoryData(); OrderProcessor orderProcessor = new OrderProcessor(informationServiceData, orderServiceData, orderRepositoryData); orderProcessor.process(orderRequest); } }
UTF-8
Java
682
java
Application.java
Java
[]
null
[]
package com.kodilla.good.patterns.orderTask; public class Application { public static void main(String[] args) { OrderRequestRetriever orderRequestRetriever = new OrderRequestRetriever(); OrderRequest orderRequest = orderRequestRetriever.retrieve(); InformationServiceData informationServiceData = new InformationServiceData(); OrderServiceData orderServiceData = new OrderServiceData(); OrderRepositoryData orderRepositoryData = new OrderRepositoryData(); OrderProcessor orderProcessor = new OrderProcessor(informationServiceData, orderServiceData, orderRepositoryData); orderProcessor.process(orderRequest); } }
682
0.768328
0.768328
16
41.625
37.695946
122
false
false
0
0
0
0
0
0
0.625
false
false
13
b95be5410bff244e51b33494291ce910e422b882
31,937,376,816,491
9dcd4c4d32004a9cd9ff13ae7ff43d589a6d42b6
/GnutellaCrawler/src/ca/ubc/ece/crawler/NodeManager.java
4038cdc0481c35a654ef733fda4c311b2d83b8d3
[]
no_license
skidson/eece411p2
https://github.com/skidson/eece411p2
3beabbd6f019b4a89bf73b4c636d1879ec72686c
798f36855e7262f1cff2e28615f55c21437a9a85
refs/heads/master
2016-09-06T07:51:52.478000
2010-12-12T07:45:47
2010-12-12T07:45:47
32,188,430
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ca.ubc.ece.crawler; import java.io.IOException; import java.io.ObjectOutputStream; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; import java.util.Vector; public class NodeManager { public static final int NUM_FELLOWSHIPS = 10; public static final int RING_SIZE = 10; public static final int TRACKER_PORT = Master.DEFAULT_PORTNUM + 2; public static final int DUMP_PORT = Master.DEFAULT_PORTNUM + 3; public static final int WAKE_PORT = Master.DEFAULT_PORTNUM + 4; private Vector<WorkerNode> nodes; /* ************ INITIALIZATION ************ */ public NodeManager(String[] nodes) { for (String address : nodes) { WorkerNode worker = new WorkerNode(address); this.nodes.add(worker); } for (int i = 0; i < getNumTotal(); i++) this.nodes.get(i).setFellowshipID(i/(getNumTotal()/NUM_FELLOWSHIPS)); } /* ************ HELPER METHODS ************ */ public void check(int index) { long time = System.currentTimeMillis(); try { Socket socket = connect(index); nodes.get(index).setLatency(System.currentTimeMillis() - time); socket.close(); nodes.get(index).setAlive(true); } catch (Exception e) { nodes.get(index).setAlive(false); } } private Vector<WorkerNode> getFellowshipList(int fellowshipID) { Vector<WorkerNode> fellowship = new Vector<WorkerNode>(); for (WorkerNode node : nodes) { if (node.getFellowshipID() == fellowshipID) fellowship.add(node); } return fellowship; } // Wakes one member of each fellowship which then wakes up a ring public void wakeFellowships() { for (int i = 0; i < NUM_FELLOWSHIPS; i++) { Vector<WorkerNode> fellowship = getFellowshipList(i); for (WorkerNode node : fellowship) { try { Socket socket = connect(node, WAKE_PORT); ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream()); // oos.writeObject(); // send this node's ip // oos.writeObject(); // send backup's ip oos.writeInt(RING_SIZE); for (WorkerNode member :fellowship) oos.writeObject(member.getAddress()); socket.close(); } catch (UnknownHostException e) { continue; } catch (IOException e) { continue; } break; } } } public void requestDump(int index) { try { Socket socket = connect(index, DUMP_PORT); socket.close(); } catch (UnknownHostException e) { } catch (IOException e) {} } private Socket connect(WorkerNode node, int port) throws UnknownHostException, IOException { Socket socket = null; socket = new Socket(InetAddress.getByName(node.getAddress()), port); return socket; } private Socket connect(WorkerNode node) throws UnknownHostException, IOException { Socket socket = null; socket = new Socket(InetAddress.getByName(node.getAddress()), TRACKER_PORT); return socket; } private Socket connect(int index) throws UnknownHostException, IOException { Socket socket = null; socket = new Socket(InetAddress.getByName(nodes.get(index).getAddress()), TRACKER_PORT); return socket; } private Socket connect(int index, int port) throws UnknownHostException, IOException { Socket socket = null; socket = new Socket(InetAddress.getByName(nodes.get(index).getAddress()), port); return socket; } public int getNumAlive() { int count = 0; for (WorkerNode node : nodes) { if (node.isAlive()) count++; } return count; } public int getNumDead() { return (getNumTotal() - getNumAlive()); } public int getNumTotal() { return nodes.size(); } public String getAddress(int index) { return nodes.get(index).getAddress(); } /* ************ EMBEDDED CLASSES ************ */ private class WorkerNode { private String address; private boolean alive; private long latency; private int fellowshipID; public WorkerNode(String address) { this.address = address; } protected void setLatency(long latency) { this.latency = latency; } protected void setAlive(boolean alive) { this.alive = alive; } protected void setFellowshipID(int fellowshipID) { this.fellowshipID = fellowshipID; } public String getAddress() { return this.address; } public long getLatency() { return this.latency; } public int getFellowshipID() { return this.fellowshipID; } public boolean isAlive() { return this.alive; } } }
UTF-8
Java
4,512
java
NodeManager.java
Java
[]
null
[]
package ca.ubc.ece.crawler; import java.io.IOException; import java.io.ObjectOutputStream; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; import java.util.Vector; public class NodeManager { public static final int NUM_FELLOWSHIPS = 10; public static final int RING_SIZE = 10; public static final int TRACKER_PORT = Master.DEFAULT_PORTNUM + 2; public static final int DUMP_PORT = Master.DEFAULT_PORTNUM + 3; public static final int WAKE_PORT = Master.DEFAULT_PORTNUM + 4; private Vector<WorkerNode> nodes; /* ************ INITIALIZATION ************ */ public NodeManager(String[] nodes) { for (String address : nodes) { WorkerNode worker = new WorkerNode(address); this.nodes.add(worker); } for (int i = 0; i < getNumTotal(); i++) this.nodes.get(i).setFellowshipID(i/(getNumTotal()/NUM_FELLOWSHIPS)); } /* ************ HELPER METHODS ************ */ public void check(int index) { long time = System.currentTimeMillis(); try { Socket socket = connect(index); nodes.get(index).setLatency(System.currentTimeMillis() - time); socket.close(); nodes.get(index).setAlive(true); } catch (Exception e) { nodes.get(index).setAlive(false); } } private Vector<WorkerNode> getFellowshipList(int fellowshipID) { Vector<WorkerNode> fellowship = new Vector<WorkerNode>(); for (WorkerNode node : nodes) { if (node.getFellowshipID() == fellowshipID) fellowship.add(node); } return fellowship; } // Wakes one member of each fellowship which then wakes up a ring public void wakeFellowships() { for (int i = 0; i < NUM_FELLOWSHIPS; i++) { Vector<WorkerNode> fellowship = getFellowshipList(i); for (WorkerNode node : fellowship) { try { Socket socket = connect(node, WAKE_PORT); ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream()); // oos.writeObject(); // send this node's ip // oos.writeObject(); // send backup's ip oos.writeInt(RING_SIZE); for (WorkerNode member :fellowship) oos.writeObject(member.getAddress()); socket.close(); } catch (UnknownHostException e) { continue; } catch (IOException e) { continue; } break; } } } public void requestDump(int index) { try { Socket socket = connect(index, DUMP_PORT); socket.close(); } catch (UnknownHostException e) { } catch (IOException e) {} } private Socket connect(WorkerNode node, int port) throws UnknownHostException, IOException { Socket socket = null; socket = new Socket(InetAddress.getByName(node.getAddress()), port); return socket; } private Socket connect(WorkerNode node) throws UnknownHostException, IOException { Socket socket = null; socket = new Socket(InetAddress.getByName(node.getAddress()), TRACKER_PORT); return socket; } private Socket connect(int index) throws UnknownHostException, IOException { Socket socket = null; socket = new Socket(InetAddress.getByName(nodes.get(index).getAddress()), TRACKER_PORT); return socket; } private Socket connect(int index, int port) throws UnknownHostException, IOException { Socket socket = null; socket = new Socket(InetAddress.getByName(nodes.get(index).getAddress()), port); return socket; } public int getNumAlive() { int count = 0; for (WorkerNode node : nodes) { if (node.isAlive()) count++; } return count; } public int getNumDead() { return (getNumTotal() - getNumAlive()); } public int getNumTotal() { return nodes.size(); } public String getAddress(int index) { return nodes.get(index).getAddress(); } /* ************ EMBEDDED CLASSES ************ */ private class WorkerNode { private String address; private boolean alive; private long latency; private int fellowshipID; public WorkerNode(String address) { this.address = address; } protected void setLatency(long latency) { this.latency = latency; } protected void setAlive(boolean alive) { this.alive = alive; } protected void setFellowshipID(int fellowshipID) { this.fellowshipID = fellowshipID; } public String getAddress() { return this.address; } public long getLatency() { return this.latency; } public int getFellowshipID() { return this.fellowshipID; } public boolean isAlive() { return this.alive; } } }
4,512
0.661791
0.659574
158
26.556963
23.582468
93
false
false
0
0
0
0
0
0
2.398734
false
false
13
1b3528c488672183a86023bb88811db61b7f9b15
11,158,325,074,618
95e944448000c08dd3d6915abb468767c9f29d3c
/sources/com/bytedance/android/live/uikit/p175c/C3513b.java
b2590b08a57b6a6de907c38de1269ac6bc62a0f4
[]
no_license
xrealm/tiktok-src
https://github.com/xrealm/tiktok-src
261b1faaf7b39d64bb7cb4106dc1a35963bd6868
90f305b5f981d39cfb313d75ab231326c9fca597
refs/heads/master
2022-11-12T06:43:07.401000
2020-07-04T20:21:12
2020-07-04T20:21:12
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.bytedance.android.live.uikit.p175c; import android.animation.Animator; import android.animation.Animator.AnimatorListener; import android.animation.AnimatorSet; import android.os.Handler; import android.os.Looper; import android.os.Message; import java.util.LinkedList; import java.util.Queue; /* renamed from: com.bytedance.android.live.uikit.c.b */ public final class C3513b extends Handler { /* renamed from: c */ private static C3513b f10394c; /* renamed from: a */ public boolean f10395a; /* renamed from: b */ public int f10396b = 5; /* renamed from: d */ private final Queue<C3511a> f10397d = new LinkedList(); public final void dismiss() { C3511a aVar = (C3511a) this.f10397d.peek(); if (aVar != null) { aVar.dismiss(); } } /* renamed from: a */ public static synchronized C3513b m12951a() { synchronized (C3513b.class) { if (f10394c != null) { C3513b bVar = f10394c; return bVar; } C3513b bVar2 = new C3513b(Looper.getMainLooper()); f10394c = bVar2; return bVar2; } } /* renamed from: b */ private void m12952b() { while (!this.f10397d.isEmpty()) { C3511a aVar = (C3511a) this.f10397d.peek(); if (aVar.mo10606g()) { aVar.dismiss(); this.f10397d.poll(); } else { if (!aVar.mo10601c()) { Message obtain = Message.obtain(); obtain.what = 291; obtain.obj = aVar; sendMessage(obtain); } return; } } } private C3513b(Looper looper) { super(looper); } /* renamed from: b */ public final void mo10609b(C3511a aVar) { this.f10397d.remove(aVar); while (this.f10397d.contains(aVar)) { this.f10397d.remove(aVar); } } public final void handleMessage(Message message) { C3511a aVar = (C3511a) message.obj; int i = message.what; if (i == 291) { m12953d(aVar); } else if (i != 1110) { if (i == 1929) { m12952b(); } } else { mo10610c(aVar); } } /* renamed from: d */ private void m12953d(C3511a aVar) { if (!aVar.mo10601c()) { aVar.mo10605f(); this.f10395a = true; aVar.mo10593a().start(); Message obtain = Message.obtain(); obtain.what = 1110; obtain.obj = aVar; sendMessageDelayed(obtain, aVar.f10368b); } } /* renamed from: a */ public final void mo10608a(C3511a aVar) { if (!this.f10397d.contains(aVar) && this.f10397d.size() <= this.f10396b) { this.f10397d.offer(aVar); if (!this.f10395a) { m12952b(); } } } /* renamed from: c */ public final void mo10610c(final C3511a aVar) { if (!aVar.mo10601c() || aVar.mo10606g()) { aVar.dismiss(); this.f10395a = false; this.f10397d.remove(aVar); sendEmptyMessage(1929); } else if (!this.f10397d.contains(aVar)) { this.f10395a = false; removeMessages(1110); sendEmptyMessage(1929); } else { AnimatorSet b = aVar.mo10599b(); b.addListener(new AnimatorListener() { public final void onAnimationCancel(Animator animator) { } public final void onAnimationRepeat(Animator animator) { } public final void onAnimationStart(Animator animator) { aVar.f10370d = true; } public final void onAnimationEnd(Animator animator) { aVar.f10370d = false; aVar.dismiss(); C3513b.this.f10395a = false; C3513b.this.removeMessages(1110); C3513b.this.sendEmptyMessage(1929); } }); b.start(); this.f10397d.poll(); } } }
UTF-8
Java
4,305
java
C3513b.java
Java
[]
null
[]
package com.bytedance.android.live.uikit.p175c; import android.animation.Animator; import android.animation.Animator.AnimatorListener; import android.animation.AnimatorSet; import android.os.Handler; import android.os.Looper; import android.os.Message; import java.util.LinkedList; import java.util.Queue; /* renamed from: com.bytedance.android.live.uikit.c.b */ public final class C3513b extends Handler { /* renamed from: c */ private static C3513b f10394c; /* renamed from: a */ public boolean f10395a; /* renamed from: b */ public int f10396b = 5; /* renamed from: d */ private final Queue<C3511a> f10397d = new LinkedList(); public final void dismiss() { C3511a aVar = (C3511a) this.f10397d.peek(); if (aVar != null) { aVar.dismiss(); } } /* renamed from: a */ public static synchronized C3513b m12951a() { synchronized (C3513b.class) { if (f10394c != null) { C3513b bVar = f10394c; return bVar; } C3513b bVar2 = new C3513b(Looper.getMainLooper()); f10394c = bVar2; return bVar2; } } /* renamed from: b */ private void m12952b() { while (!this.f10397d.isEmpty()) { C3511a aVar = (C3511a) this.f10397d.peek(); if (aVar.mo10606g()) { aVar.dismiss(); this.f10397d.poll(); } else { if (!aVar.mo10601c()) { Message obtain = Message.obtain(); obtain.what = 291; obtain.obj = aVar; sendMessage(obtain); } return; } } } private C3513b(Looper looper) { super(looper); } /* renamed from: b */ public final void mo10609b(C3511a aVar) { this.f10397d.remove(aVar); while (this.f10397d.contains(aVar)) { this.f10397d.remove(aVar); } } public final void handleMessage(Message message) { C3511a aVar = (C3511a) message.obj; int i = message.what; if (i == 291) { m12953d(aVar); } else if (i != 1110) { if (i == 1929) { m12952b(); } } else { mo10610c(aVar); } } /* renamed from: d */ private void m12953d(C3511a aVar) { if (!aVar.mo10601c()) { aVar.mo10605f(); this.f10395a = true; aVar.mo10593a().start(); Message obtain = Message.obtain(); obtain.what = 1110; obtain.obj = aVar; sendMessageDelayed(obtain, aVar.f10368b); } } /* renamed from: a */ public final void mo10608a(C3511a aVar) { if (!this.f10397d.contains(aVar) && this.f10397d.size() <= this.f10396b) { this.f10397d.offer(aVar); if (!this.f10395a) { m12952b(); } } } /* renamed from: c */ public final void mo10610c(final C3511a aVar) { if (!aVar.mo10601c() || aVar.mo10606g()) { aVar.dismiss(); this.f10395a = false; this.f10397d.remove(aVar); sendEmptyMessage(1929); } else if (!this.f10397d.contains(aVar)) { this.f10395a = false; removeMessages(1110); sendEmptyMessage(1929); } else { AnimatorSet b = aVar.mo10599b(); b.addListener(new AnimatorListener() { public final void onAnimationCancel(Animator animator) { } public final void onAnimationRepeat(Animator animator) { } public final void onAnimationStart(Animator animator) { aVar.f10370d = true; } public final void onAnimationEnd(Animator animator) { aVar.f10370d = false; aVar.dismiss(); C3513b.this.f10395a = false; C3513b.this.removeMessages(1110); C3513b.this.sendEmptyMessage(1929); } }); b.start(); this.f10397d.poll(); } } }
4,305
0.507317
0.421835
151
27.509933
18.284313
82
false
false
0
0
0
0
0
0
0.430464
false
false
13
2868e39da7a9553f2a4b8282eed6cadca92e15a7
29,111,288,347,681
d1970587e1b1889388c288202c835e96e8c25e90
/22.Web_MVC_framework/22.5.Resolving_views/22.5.4.ContentNegotiatingViewResolver/src/main/java/com/qiaogh/view/ExcelView.java
2ce7ec03d969883a629ecd8ce39a8c55ca2c2e76
[]
no_license
Qiaogh/Spring
https://github.com/Qiaogh/Spring
fb3225e050e96dba50b7998809c2ed9204d08926
b894dd3c47af489ba88f29bdd959bd4607de697f
refs/heads/master
2021-08-07T07:08:34.880000
2018-02-22T13:48:59
2018-02-22T13:48:59
95,947,202
0
1
null
false
2017-07-05T08:31:18
2017-07-01T06:44:01
2017-07-01T09:19:48
2017-07-05T08:29:58
64
0
1
0
Java
null
null
package com.qiaogh.view; import com.qiaogh.domain.User; import org.apache.poi.ss.usermodel.*; import org.springframework.web.servlet.view.document.AbstractXlsView; import org.springframework.web.servlet.view.document.AbstractXlsxView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Map; public class ExcelView extends AbstractXlsView { @Override protected void buildExcelDocument( Map<String, Object> model, Workbook workbook, HttpServletRequest request, HttpServletResponse response ) throws Exception { User user = (User) model.get( "user" ); Sheet sheet = workbook.createSheet( "用户信息" ); CellStyle cellStyle = workbook.createCellStyle(); cellStyle.setFillForegroundColor( IndexedColors.GREEN.index ); cellStyle.setFillPattern( FillPatternType.SOLID_FOREGROUND ); cellStyle.setAlignment( HorizontalAlignment.CENTER ); Row row = sheet.createRow( 0 ); Cell cell = row.createCell( 0 ); cell.setCellStyle( cellStyle ); cell.setCellValue( "Id" ); cell = row.createCell( 1 ); cell.setCellStyle( cellStyle ); cell.setCellValue( "Name" ); cell = row.createCell( 2 ); cell.setCellStyle( cellStyle ); cell.setCellValue( "Password" ); row = sheet.createRow( 1 ); cell = row.createCell( 0 ); cell.setCellStyle( cellStyle ); cell.setCellValue( user.getId() ); cell = row.createCell( 1 ); cell.setCellStyle( cellStyle ); cell.setCellValue( user.getName() ); cell = row.createCell( 2 ); cell.setCellStyle( cellStyle ); cell.setCellValue( user.getPassword() ); for ( int i = 0; i < 3; i++ ) { sheet.autoSizeColumn( i, true ); } } }
UTF-8
Java
1,968
java
ExcelView.java
Java
[]
null
[]
package com.qiaogh.view; import com.qiaogh.domain.User; import org.apache.poi.ss.usermodel.*; import org.springframework.web.servlet.view.document.AbstractXlsView; import org.springframework.web.servlet.view.document.AbstractXlsxView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Map; public class ExcelView extends AbstractXlsView { @Override protected void buildExcelDocument( Map<String, Object> model, Workbook workbook, HttpServletRequest request, HttpServletResponse response ) throws Exception { User user = (User) model.get( "user" ); Sheet sheet = workbook.createSheet( "用户信息" ); CellStyle cellStyle = workbook.createCellStyle(); cellStyle.setFillForegroundColor( IndexedColors.GREEN.index ); cellStyle.setFillPattern( FillPatternType.SOLID_FOREGROUND ); cellStyle.setAlignment( HorizontalAlignment.CENTER ); Row row = sheet.createRow( 0 ); Cell cell = row.createCell( 0 ); cell.setCellStyle( cellStyle ); cell.setCellValue( "Id" ); cell = row.createCell( 1 ); cell.setCellStyle( cellStyle ); cell.setCellValue( "Name" ); cell = row.createCell( 2 ); cell.setCellStyle( cellStyle ); cell.setCellValue( "Password" ); row = sheet.createRow( 1 ); cell = row.createCell( 0 ); cell.setCellStyle( cellStyle ); cell.setCellValue( user.getId() ); cell = row.createCell( 1 ); cell.setCellStyle( cellStyle ); cell.setCellValue( user.getName() ); cell = row.createCell( 2 ); cell.setCellStyle( cellStyle ); cell.setCellValue( user.getPassword() ); for ( int i = 0; i < 3; i++ ) { sheet.autoSizeColumn( i, true ); } } }
1,968
0.617857
0.612755
59
32.220341
23.560286
88
false
false
0
0
0
0
0
0
0.711864
false
false
13
7c555f21ac7fad7fc914c93432ea58f0dfa9c451
2,714,419,370,497
cefd8a710ec829b2f67ffbebd61e77a0fd02c039
/lexer/src/se/jocke/nb/docker/lexer/DockerParser.java
4f8eb09810f77c68f5a72479bfe414f309f66c76
[]
no_license
jockeeriksson/nbdocker
https://github.com/jockeeriksson/nbdocker
8fe47dfbdda26265e007d7771fb40c3f91595b6e
b8eb5eeeffb084f98c9b8f7d0cb88bfe147a999f
refs/heads/master
2016-09-06T06:47:01.311000
2015-01-13T22:51:18
2015-01-13T22:51:18
28,003,838
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* Generated By:JavaCC: Do not edit this line. DockerParser.java */ package se.jocke.nb.docker.lexer; import java.io.*; public class DockerParser implements DockerParserConstants { final public void CompilationUnit() throws ParseException { expression(); } final public void expression() throws ParseException { label_1: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case FROM: case MAINTAINER: case RUN: case CMD: case EXPOSE: case ENV: case ADD: case COPY: case ENTRYPOINT: case VOLUME: case USER: case WORKDIR: case ONBUILD: ; break; default: break label_1; } stmt(); sep(); string(); jj_consume_token(LN); } jj_consume_token(0); } final public void stmt() throws ParseException { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case FROM: jj_consume_token(FROM); break; case MAINTAINER: jj_consume_token(MAINTAINER); break; case RUN: jj_consume_token(RUN); break; case CMD: jj_consume_token(CMD); break; case EXPOSE: jj_consume_token(EXPOSE); break; case ENV: jj_consume_token(ENV); break; case ADD: jj_consume_token(ADD); break; case COPY: jj_consume_token(COPY); break; case ENTRYPOINT: jj_consume_token(ENTRYPOINT); break; case VOLUME: jj_consume_token(VOLUME); break; case USER: jj_consume_token(USER); break; case WORKDIR: jj_consume_token(WORKDIR); break; case ONBUILD: jj_consume_token(ONBUILD); break; default: jj_consume_token(-1); throw new ParseException(); } } final public void string() throws ParseException { jj_consume_token(STRING); } final public void sep() throws ParseException { jj_consume_token(SEP); } /** Generated Token Manager. */ public DockerParserTokenManager token_source; JavaCharStream jj_input_stream; /** Current token. */ public Token token; /** Next token. */ public Token jj_nt; private int jj_ntk; /** Constructor with InputStream. */ public DockerParser(java.io.InputStream stream) { this(stream, null); } /** Constructor with InputStream and supplied encoding */ public DockerParser(java.io.InputStream stream, String encoding) { try { jj_input_stream = new JavaCharStream(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); } token_source = new DockerParserTokenManager(jj_input_stream); token = new Token(); jj_ntk = -1; } /** Reinitialise. */ public void ReInit(java.io.InputStream stream) { ReInit(stream, null); } /** Reinitialise. */ public void ReInit(java.io.InputStream stream, String encoding) { try { jj_input_stream.ReInit(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); } token_source.ReInit(jj_input_stream); token = new Token(); jj_ntk = -1; } /** Constructor. */ public DockerParser(java.io.Reader stream) { jj_input_stream = new JavaCharStream(stream, 1, 1); token_source = new DockerParserTokenManager(jj_input_stream); token = new Token(); jj_ntk = -1; } /** Reinitialise. */ public void ReInit(java.io.Reader stream) { jj_input_stream.ReInit(stream, 1, 1); token_source.ReInit(jj_input_stream); token = new Token(); jj_ntk = -1; } /** Constructor with generated Token Manager. */ public DockerParser(DockerParserTokenManager tm) { token_source = tm; token = new Token(); jj_ntk = -1; } /** Reinitialise. */ public void ReInit(DockerParserTokenManager tm) { token_source = tm; token = new Token(); jj_ntk = -1; } private Token jj_consume_token(int kind) throws ParseException { Token oldToken; if ((oldToken = token).next != null) token = token.next; else token = token.next = token_source.getNextToken(); jj_ntk = -1; if (token.kind == kind) { return token; } token = oldToken; throw generateParseException(); } /** Get the next Token. */ final public Token getNextToken() { if (token.next != null) token = token.next; else token = token.next = token_source.getNextToken(); jj_ntk = -1; return token; } /** Get the specific Token. */ final public Token getToken(int index) { Token t = token; for (int i = 0; i < index; i++) { if (t.next != null) t = t.next; else t = t.next = token_source.getNextToken(); } return t; } private int jj_ntk() { if ((jj_nt=token.next) == null) return (jj_ntk = (token.next=token_source.getNextToken()).kind); else return (jj_ntk = jj_nt.kind); } /** Generate ParseException. */ public ParseException generateParseException() { Token errortok = token.next; int line = errortok.beginLine, column = errortok.beginColumn; String mess = (errortok.kind == 0) ? tokenImage[0] : errortok.image; return new ParseException("Parse error at line " + line + ", column " + column + ". Encountered: " + mess); } /** Enable tracing. */ final public void enable_tracing() { } /** Disable tracing. */ final public void disable_tracing() { } }
UTF-8
Java
5,421
java
DockerParser.java
Java
[]
null
[]
/* Generated By:JavaCC: Do not edit this line. DockerParser.java */ package se.jocke.nb.docker.lexer; import java.io.*; public class DockerParser implements DockerParserConstants { final public void CompilationUnit() throws ParseException { expression(); } final public void expression() throws ParseException { label_1: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case FROM: case MAINTAINER: case RUN: case CMD: case EXPOSE: case ENV: case ADD: case COPY: case ENTRYPOINT: case VOLUME: case USER: case WORKDIR: case ONBUILD: ; break; default: break label_1; } stmt(); sep(); string(); jj_consume_token(LN); } jj_consume_token(0); } final public void stmt() throws ParseException { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case FROM: jj_consume_token(FROM); break; case MAINTAINER: jj_consume_token(MAINTAINER); break; case RUN: jj_consume_token(RUN); break; case CMD: jj_consume_token(CMD); break; case EXPOSE: jj_consume_token(EXPOSE); break; case ENV: jj_consume_token(ENV); break; case ADD: jj_consume_token(ADD); break; case COPY: jj_consume_token(COPY); break; case ENTRYPOINT: jj_consume_token(ENTRYPOINT); break; case VOLUME: jj_consume_token(VOLUME); break; case USER: jj_consume_token(USER); break; case WORKDIR: jj_consume_token(WORKDIR); break; case ONBUILD: jj_consume_token(ONBUILD); break; default: jj_consume_token(-1); throw new ParseException(); } } final public void string() throws ParseException { jj_consume_token(STRING); } final public void sep() throws ParseException { jj_consume_token(SEP); } /** Generated Token Manager. */ public DockerParserTokenManager token_source; JavaCharStream jj_input_stream; /** Current token. */ public Token token; /** Next token. */ public Token jj_nt; private int jj_ntk; /** Constructor with InputStream. */ public DockerParser(java.io.InputStream stream) { this(stream, null); } /** Constructor with InputStream and supplied encoding */ public DockerParser(java.io.InputStream stream, String encoding) { try { jj_input_stream = new JavaCharStream(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); } token_source = new DockerParserTokenManager(jj_input_stream); token = new Token(); jj_ntk = -1; } /** Reinitialise. */ public void ReInit(java.io.InputStream stream) { ReInit(stream, null); } /** Reinitialise. */ public void ReInit(java.io.InputStream stream, String encoding) { try { jj_input_stream.ReInit(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); } token_source.ReInit(jj_input_stream); token = new Token(); jj_ntk = -1; } /** Constructor. */ public DockerParser(java.io.Reader stream) { jj_input_stream = new JavaCharStream(stream, 1, 1); token_source = new DockerParserTokenManager(jj_input_stream); token = new Token(); jj_ntk = -1; } /** Reinitialise. */ public void ReInit(java.io.Reader stream) { jj_input_stream.ReInit(stream, 1, 1); token_source.ReInit(jj_input_stream); token = new Token(); jj_ntk = -1; } /** Constructor with generated Token Manager. */ public DockerParser(DockerParserTokenManager tm) { token_source = tm; token = new Token(); jj_ntk = -1; } /** Reinitialise. */ public void ReInit(DockerParserTokenManager tm) { token_source = tm; token = new Token(); jj_ntk = -1; } private Token jj_consume_token(int kind) throws ParseException { Token oldToken; if ((oldToken = token).next != null) token = token.next; else token = token.next = token_source.getNextToken(); jj_ntk = -1; if (token.kind == kind) { return token; } token = oldToken; throw generateParseException(); } /** Get the next Token. */ final public Token getNextToken() { if (token.next != null) token = token.next; else token = token.next = token_source.getNextToken(); jj_ntk = -1; return token; } /** Get the specific Token. */ final public Token getToken(int index) { Token t = token; for (int i = 0; i < index; i++) { if (t.next != null) t = t.next; else t = t.next = token_source.getNextToken(); } return t; } private int jj_ntk() { if ((jj_nt=token.next) == null) return (jj_ntk = (token.next=token_source.getNextToken()).kind); else return (jj_ntk = jj_nt.kind); } /** Generate ParseException. */ public ParseException generateParseException() { Token errortok = token.next; int line = errortok.beginLine, column = errortok.beginColumn; String mess = (errortok.kind == 0) ? tokenImage[0] : errortok.image; return new ParseException("Parse error at line " + line + ", column " + column + ". Encountered: " + mess); } /** Enable tracing. */ final public void enable_tracing() { } /** Disable tracing. */ final public void disable_tracing() { } }
5,421
0.615016
0.610404
214
24.331776
22.452385
154
false
false
0
0
0
0
0
0
0.518692
false
false
13
ab46ee54a96a45af3d5645d8cb6405bdcaa8d142
22,445,499,092,077
5aa75c73a54ecaf32cdfc305521fc0a70cb2d473
/rent_comment_show/src/main/java/cn/dywei/service/CommentService.java
486e1c4a95b8f2eca599de40242e3c4935465597
[]
no_license
Dywei0620/RentSystem
https://github.com/Dywei0620/RentSystem
bf3c23d17648ba060c96c27b2ba272170ca46157
4909207d17c75ecfc85f03d680bf2408bace5fc7
refs/heads/master
2023-08-08T06:29:26.488000
2020-04-20T07:46:32
2020-04-20T07:46:32
256,695,100
0
0
null
false
2023-07-23T12:22:07
2020-04-18T07:32:28
2020-04-20T07:46:35
2023-07-23T12:22:07
60
0
0
2
Java
false
false
package cn.dywei.service; import cn.dywei.commons.pojo.rentResult; public interface CommentService { rentResult showComment(String id,int page,int size); }
UTF-8
Java
162
java
CommentService.java
Java
[]
null
[]
package cn.dywei.service; import cn.dywei.commons.pojo.rentResult; public interface CommentService { rentResult showComment(String id,int page,int size); }
162
0.783951
0.783951
7
22.142857
20.766928
56
false
false
0
0
0
0
0
0
0.714286
false
false
13
e07c1c5fdaa9b61db1414e42f2504d7a37860f20
22,445,499,093,072
a910dfe211d160bd5823da6ad9c85012504644b1
/src/test/java/com/vlkan/pubsub/model/PubsubPullResponseTest.java
32a769f76b39e073db9a8d5208b659adb03d6e19
[ "Apache-2.0" ]
permissive
vy/reactor-pubsub
https://github.com/vy/reactor-pubsub
bbbb7fb51c825242b390f54acf6e0186cccb3bf9
4eab7a16af79f1512c731e34744211687436cad9
refs/heads/master
2023-06-20T06:44:38.166000
2021-02-17T14:48:03
2021-02-17T14:48:03
206,168,092
28
6
Apache-2.0
false
2023-09-08T12:21:57
2019-09-03T20:38:45
2023-05-18T21:07:28
2023-09-08T12:21:56
368
29
6
9
Java
false
false
/* * Copyright 2019-2020 Volkan Yazıcı * * 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 permits and * limitations under the License. */ package com.vlkan.pubsub.model; import com.vlkan.pubsub.MapHelpers; import com.vlkan.pubsub.jackson.JacksonHelpers; import org.assertj.core.api.Assertions; import org.junit.Test; import java.time.Duration; import java.time.Instant; import java.util.Arrays; import java.util.Base64; import java.util.Collections; import java.util.List; import java.util.Map; public class PubsubPullResponseTest { @Test public void test_deserialization_with_empty_payload() { String responseJson = "{}"; PubsubPullResponse response = JacksonHelpers.readValue(responseJson, PubsubPullResponse.class); Assertions.assertThat(response.getReceivedMessages()).isEmpty(); } @Test public void test_deserialization_with_null_receivedMessages() { String responseJson = "{\"" + PubsubPullResponse.JsonFieldName.RECEIVED_MESSAGES + "\": null}"; PubsubPullResponse response = JacksonHelpers.readValue(responseJson, PubsubPullResponse.class); Assertions.assertThat(response.getReceivedMessages()).isEmpty(); } @Test public void test_deserialization_with_empty_receivedMessages() { String responseJson = "{\"" + PubsubPullResponse.JsonFieldName.RECEIVED_MESSAGES + "\": []}"; PubsubPullResponse response = JacksonHelpers.readValue(responseJson, PubsubPullResponse.class); Assertions.assertThat(response.getReceivedMessages()).isEmpty(); } @Test public void test_deserialization() { // Build a Pub/Sub pull response JSON. Instant expectedInstant1 = Instant.parse("2019-08-27T08:04:57Z"); byte[] expectedPayload1 = {1, 2, 3}; Map<String, String> expectedAttributes1 = Collections.singletonMap("key1", "val1"); Map<String, Object> expectedReceivedMessageEmbedding1Map = MapHelpers.createMap( PubsubReceivedMessageEmbedding.JsonFieldName.PUBLISH_INSTANT, expectedInstant1.toString(), PubsubReceivedMessageEmbedding.JsonFieldName.ID, "messageId1", PubsubReceivedMessageEmbedding.JsonFieldName.PAYLOAD, Base64.getEncoder().encodeToString(expectedPayload1), PubsubReceivedMessageEmbedding.JsonFieldName.ATTRIBUTES, expectedAttributes1); Map<String, Object> expectedReceivedMessage1Map = MapHelpers.createMap( PubsubReceivedMessage.JsonFieldName.ACK_ID, "ackId1", PubsubReceivedMessage.JsonFieldName.EMBEDDING, expectedReceivedMessageEmbedding1Map); Instant expectedInstant2 = expectedInstant1.plus(Duration.ofMinutes(1)); byte[] expectedPayload2 = {4, 5, 6}; Map<String, String> expectedAttributes2 = Collections.singletonMap("key2", "val2"); Map<String, Object> expectedReceivedMessageEmbedding2Map = MapHelpers.createMap( PubsubReceivedMessageEmbedding.JsonFieldName.PUBLISH_INSTANT, expectedInstant2.toString(), PubsubReceivedMessageEmbedding.JsonFieldName.ID, "messageId2", PubsubReceivedMessageEmbedding.JsonFieldName.PAYLOAD, Base64.getEncoder().encodeToString(expectedPayload2), PubsubReceivedMessageEmbedding.JsonFieldName.ATTRIBUTES, expectedAttributes2); Map<String, Object> expectedReceivedMessage2Map = MapHelpers.createMap( PubsubReceivedMessage.JsonFieldName.ACK_ID, "ackId2", PubsubReceivedMessage.JsonFieldName.EMBEDDING, expectedReceivedMessageEmbedding2Map); List<Map<String, Object>> expectedReceivedMessagesList = Arrays.asList( expectedReceivedMessage1Map, expectedReceivedMessage2Map); Map<String, Object> expectedResponseMap = Collections.singletonMap( PubsubPullResponse.JsonFieldName.RECEIVED_MESSAGES, expectedReceivedMessagesList); String responseJson = JacksonHelpers.writeValueAsString(expectedResponseMap); // Deserialize Pub/Sub pull response from the JSON. PubsubPullResponse actualResponse = JacksonHelpers.readValue(responseJson, PubsubPullResponse.class); // Build the expected response model. PubsubPullResponse expectedResponse = new PubsubPullResponse(Arrays.asList( new PubsubReceivedMessage( "ackId1", new PubsubReceivedMessageEmbedding( expectedInstant1, "messageId1", expectedPayload1, expectedAttributes1)), new PubsubReceivedMessage( "ackId2", new PubsubReceivedMessageEmbedding( expectedInstant2, "messageId2", expectedPayload2, expectedAttributes2)))); // Compare the content. Assertions.assertThat(actualResponse).isEqualTo(expectedResponse); } @Test public void test_serialization() { PubsubPullResponse pullResponse = PubsubPullResponseFixture.createRandomPullResponse(30); String pullResponseJson = JacksonHelpers.writeValueAsString(pullResponse); PubsubPullResponse deserializedPullResponse = JacksonHelpers.readValue(pullResponseJson, PubsubPullResponse.class); Assertions.assertThat(deserializedPullResponse).isEqualTo(pullResponse); } }
UTF-8
Java
6,064
java
PubsubPullResponseTest.java
Java
[ { "context": "/*\n * Copyright 2019-2020 Volkan Yazıcı\n *\n * Licensed under the Apache License, Version ", "end": 39, "score": 0.999861478805542, "start": 26, "tag": "NAME", "value": "Volkan Yazıcı" } ]
null
[]
/* * Copyright 2019-2020 <NAME> * * 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 permits and * limitations under the License. */ package com.vlkan.pubsub.model; import com.vlkan.pubsub.MapHelpers; import com.vlkan.pubsub.jackson.JacksonHelpers; import org.assertj.core.api.Assertions; import org.junit.Test; import java.time.Duration; import java.time.Instant; import java.util.Arrays; import java.util.Base64; import java.util.Collections; import java.util.List; import java.util.Map; public class PubsubPullResponseTest { @Test public void test_deserialization_with_empty_payload() { String responseJson = "{}"; PubsubPullResponse response = JacksonHelpers.readValue(responseJson, PubsubPullResponse.class); Assertions.assertThat(response.getReceivedMessages()).isEmpty(); } @Test public void test_deserialization_with_null_receivedMessages() { String responseJson = "{\"" + PubsubPullResponse.JsonFieldName.RECEIVED_MESSAGES + "\": null}"; PubsubPullResponse response = JacksonHelpers.readValue(responseJson, PubsubPullResponse.class); Assertions.assertThat(response.getReceivedMessages()).isEmpty(); } @Test public void test_deserialization_with_empty_receivedMessages() { String responseJson = "{\"" + PubsubPullResponse.JsonFieldName.RECEIVED_MESSAGES + "\": []}"; PubsubPullResponse response = JacksonHelpers.readValue(responseJson, PubsubPullResponse.class); Assertions.assertThat(response.getReceivedMessages()).isEmpty(); } @Test public void test_deserialization() { // Build a Pub/Sub pull response JSON. Instant expectedInstant1 = Instant.parse("2019-08-27T08:04:57Z"); byte[] expectedPayload1 = {1, 2, 3}; Map<String, String> expectedAttributes1 = Collections.singletonMap("key1", "val1"); Map<String, Object> expectedReceivedMessageEmbedding1Map = MapHelpers.createMap( PubsubReceivedMessageEmbedding.JsonFieldName.PUBLISH_INSTANT, expectedInstant1.toString(), PubsubReceivedMessageEmbedding.JsonFieldName.ID, "messageId1", PubsubReceivedMessageEmbedding.JsonFieldName.PAYLOAD, Base64.getEncoder().encodeToString(expectedPayload1), PubsubReceivedMessageEmbedding.JsonFieldName.ATTRIBUTES, expectedAttributes1); Map<String, Object> expectedReceivedMessage1Map = MapHelpers.createMap( PubsubReceivedMessage.JsonFieldName.ACK_ID, "ackId1", PubsubReceivedMessage.JsonFieldName.EMBEDDING, expectedReceivedMessageEmbedding1Map); Instant expectedInstant2 = expectedInstant1.plus(Duration.ofMinutes(1)); byte[] expectedPayload2 = {4, 5, 6}; Map<String, String> expectedAttributes2 = Collections.singletonMap("key2", "val2"); Map<String, Object> expectedReceivedMessageEmbedding2Map = MapHelpers.createMap( PubsubReceivedMessageEmbedding.JsonFieldName.PUBLISH_INSTANT, expectedInstant2.toString(), PubsubReceivedMessageEmbedding.JsonFieldName.ID, "messageId2", PubsubReceivedMessageEmbedding.JsonFieldName.PAYLOAD, Base64.getEncoder().encodeToString(expectedPayload2), PubsubReceivedMessageEmbedding.JsonFieldName.ATTRIBUTES, expectedAttributes2); Map<String, Object> expectedReceivedMessage2Map = MapHelpers.createMap( PubsubReceivedMessage.JsonFieldName.ACK_ID, "ackId2", PubsubReceivedMessage.JsonFieldName.EMBEDDING, expectedReceivedMessageEmbedding2Map); List<Map<String, Object>> expectedReceivedMessagesList = Arrays.asList( expectedReceivedMessage1Map, expectedReceivedMessage2Map); Map<String, Object> expectedResponseMap = Collections.singletonMap( PubsubPullResponse.JsonFieldName.RECEIVED_MESSAGES, expectedReceivedMessagesList); String responseJson = JacksonHelpers.writeValueAsString(expectedResponseMap); // Deserialize Pub/Sub pull response from the JSON. PubsubPullResponse actualResponse = JacksonHelpers.readValue(responseJson, PubsubPullResponse.class); // Build the expected response model. PubsubPullResponse expectedResponse = new PubsubPullResponse(Arrays.asList( new PubsubReceivedMessage( "ackId1", new PubsubReceivedMessageEmbedding( expectedInstant1, "messageId1", expectedPayload1, expectedAttributes1)), new PubsubReceivedMessage( "ackId2", new PubsubReceivedMessageEmbedding( expectedInstant2, "messageId2", expectedPayload2, expectedAttributes2)))); // Compare the content. Assertions.assertThat(actualResponse).isEqualTo(expectedResponse); } @Test public void test_serialization() { PubsubPullResponse pullResponse = PubsubPullResponseFixture.createRandomPullResponse(30); String pullResponseJson = JacksonHelpers.writeValueAsString(pullResponse); PubsubPullResponse deserializedPullResponse = JacksonHelpers.readValue(pullResponseJson, PubsubPullResponse.class); Assertions.assertThat(deserializedPullResponse).isEqualTo(pullResponse); } }
6,055
0.688387
0.67519
124
47.887096
34.199181
123
false
false
0
0
0
0
0
0
0.774194
false
false
13
e0d351ee34c6e25f647b2fcd6469edd4ee97c0a8
20,675,972,567,992
37d435f901637468863a831d48335939e711417c
/app/src/main/java/com/example/admin/movehackv2/MainActivity.java
6216cd388371cae095a5996b993c5ce809557f25
[]
no_license
jeetpateljsp/Movehackv2
https://github.com/jeetpateljsp/Movehackv2
19be7b508dd13ace3d027a128b4aed9c34b640d5
7e1309c171fe34423e62bc5ef01ad1902830ab8d
refs/heads/master
2020-03-27T11:16:19.178000
2018-08-28T16:25:08
2018-08-28T16:25:08
146,475,117
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.admin.movehackv2; import android.support.v4.app.Fragment; import android.support.annotation.NonNull; import android.support.design.widget.BottomNavigationView; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.MenuItem; import android.widget.FrameLayout; public class MainActivity extends AppCompatActivity { private Home homeFragment; private Notification notificationFragment; private Info infoFragment; private BottomNavigationView main_view; private FrameLayout main_frame; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); main_view = (BottomNavigationView) findViewById(R.id.main_nav); main_frame = (FrameLayout) findViewById(R.id.main_frame); homeFragment = new Home(); notificationFragment = new Notification(); infoFragment = new Info(); setFragment(new Home()); main_view.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(MenuItem item) { switch (item.getItemId()){ case R.id.home: setFragment(new Home()); return true; case R.id.notify: setFragment(new Notification()); return true; case R.id.info: setFragment(new Info()); return true; default : return false; } } }); } private void setFragment(Fragment fragment) { FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); fragmentTransaction.replace(R.id.main_frame, fragment).commit(); } }
UTF-8
Java
2,131
java
MainActivity.java
Java
[]
null
[]
package com.example.admin.movehackv2; import android.support.v4.app.Fragment; import android.support.annotation.NonNull; import android.support.design.widget.BottomNavigationView; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.MenuItem; import android.widget.FrameLayout; public class MainActivity extends AppCompatActivity { private Home homeFragment; private Notification notificationFragment; private Info infoFragment; private BottomNavigationView main_view; private FrameLayout main_frame; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); main_view = (BottomNavigationView) findViewById(R.id.main_nav); main_frame = (FrameLayout) findViewById(R.id.main_frame); homeFragment = new Home(); notificationFragment = new Notification(); infoFragment = new Info(); setFragment(new Home()); main_view.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(MenuItem item) { switch (item.getItemId()){ case R.id.home: setFragment(new Home()); return true; case R.id.notify: setFragment(new Notification()); return true; case R.id.info: setFragment(new Info()); return true; default : return false; } } }); } private void setFragment(Fragment fragment) { FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); fragmentTransaction.replace(R.id.main_frame, fragment).commit(); } }
2,131
0.610042
0.608165
69
28.884058
25.673838
115
false
false
0
0
0
0
0
0
0.478261
false
false
13
9556f4ea43271ef5e89370cf64be3e6a9685015b
12,652,973,717,355
a924fb5197accad5f3e9dc3ac7cff9f3ec010b96
/Mapa/Pixel.java
d87adaac350880dc808fa299a0b53e67c5b2ce6b
[]
no_license
Rod634/ADS
https://github.com/Rod634/ADS
35c468527fb174b476302232ebb25810219e9385
c5da3bdee60d4d66d639b399bc429fa2674def03
refs/heads/master
2020-09-25T04:20:54.734000
2020-03-05T12:26:12
2020-03-05T12:26:12
225,916,506
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
public class Pixel { }
UTF-8
Java
28
java
Pixel.java
Java
[]
null
[]
public class Pixel { }
28
0.571429
0.571429
4
6
7.035624
18
false
false
0
0
0
0
0
0
0
false
false
13
5ce22b551828fe41ab8370b2d72695e9fe6388ab
26,388,279,134,875
03d47df97c981bfc17c13711428b47740fa1ba69
/Dungeon/src/dungeon/level/Room.java
23908c50cd6f91c90db9fee93fe4076229fb07b4
[]
no_license
Delwaulle/Dungeon
https://github.com/Delwaulle/Dungeon
c9b91a285e136502a50c2e541ba792018e605b3d
595e743bf121f782f43270eb6ee2643390d400d1
refs/heads/master
2021-01-10T18:24:24.611000
2015-10-08T23:05:43
2015-10-08T23:05:43
42,250,168
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package dungeon.level; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import dungeon.items.Furniture; import dungeon.commands.CommandFactory; import dungeon.commands.Mod; import dungeon.game.GameBoard; import dungeon.game.Player; import dungeon.items.Item; import dungeon.utils.RandomGenerator; import dungeon.utils.SecureInput; /** * Each elements which composed a level * It contains door(s),monster,treasoure and some actions with decor * @author Loic * */ public abstract class Room { protected Map<Door,Room> neighbours = new HashMap<>(); protected List<Furniture> furnitures; //generate random pllls protected String name; protected Level level; protected boolean isDescribed; private CommandFactory commandFactory; protected Player player = GameBoard.player; /** * construct a room with a name and the level which the room is inside * @param name * @param level */ public Room(String name,Level level){ this.name=name; this.level=level; this.furnitures=RandomGenerator.generateRandomFurnitureList(); } /** * We show to the player all the directions he can go now */ public void displayDirections(){ System.out.println("Possible(s) direction(s) :"); String directions="-- "; Set<Door> listKeys=this.neighbours.keySet(); // key list of the map Iterator<Door> iterateur=listKeys.iterator(); while(iterateur.hasNext()) { Door key= (Door) iterateur.next(); directions+=key.getDirection().toString()+" -- "; } System.out.println(directions); } /** * set a neighbor between two rooms * @param door * @param neighbour */ public void setNeighbour(Door door, Room neighbour){ if(isValidDirection(door.getDirection())) neighbours.put(door,neighbour); } /** * @param direction * @return if the direction not exist in the room */ public boolean isValidDirection(Direction direction){ boolean valid =true; for(Door doorToCompare : this.neighbours.keySet()){ if(doorToCompare.getDirection().equals(direction)) valid=false; } return valid; } /** * @param direction * @return the direction of the player */ public Room goToDirection(Direction direction){ Door door = validDirection(direction,this.neighbours); // test if the direction is possible if(door!=null){ if(door.isLocked()){ if(!this.player.getInventory().isPresent(Item.KEY)){ System.out.println("Sorry you don't have the key to open this door, keep digging around this room"); return null; } else{ this.player.getInventory().useItem(Item.KEY); System.out.println("Good game you have the key to open this door ! You discover a new room !"); } } if(door.isHidden()){ System.out.println("you are a lucky guy you find an hidden door"); } Room nextRoom = neighbours.get(door); //set the neighboor to back in the previous room Direction oppositeDirection=direction.getOppositeDirection(); if(validDirection(oppositeDirection, nextRoom.neighbours)==null){ nextRoom.setNeighbour(new Door(oppositeDirection), this); } return nextRoom; } else return null; } /** * for each Door we look at the direction * @param direction * @param directions * @return */ public Door validDirection(Direction direction,Map<Door, Room> directions){ for(Door door : directions.keySet()){ if(door.getDirection().equals(direction)) return door; } return null; } /** * If the player asks the description of the room : * set the boolean isDescribed to true * display all the objects in the room * show all actions possible with this objects */ public void askDescription(){ this.isDescribed=true; System.out.println("There are in this room : "); if(furnitures.size()==0){ System.out.println("No furniture in this room !"); } else{ for (Furniture furniture : furnitures){ System.out.println("- "+furniture.getFurniture().name()); } this.commandFactory=new CommandFactory(Mod.EXCAVATION_MOD); System.out.println("Now you can examine the furnitures"); examineFurniture(); } } /** * verify if the furniture to examine is correct and call the action associate with it */ public void examineFurniture(){ System.out.println("What do you want to do ? (Enter help to show all the possible commands)"); System.out.print("> "); String line = SecureInput.getNoEmptyStringInput(); String[] cmd = line.split(" ",2); Furniture furniture=null; if(cmd.length!=1 && cmd[0].equals("examine")){ for(Furniture f : furnitures){ if(f.getFurniture().name().equals(cmd[1].toUpperCase())) furniture=f; } if(furniture==null){ System.out.println("Invalid furniture, please try again"); examineFurniture(); } } if(!this.commandFactory.interpretCommand(cmd, this.player, this.level, this,null, furniture)) this.examineFurniture(); } /** * @return the name of the room */ public String getName(){ return this.name; } /** * @return if the player asks the description of the room */ public boolean isDescribed() { return isDescribed; } /** * only used for tests * @param player */ public void setPlayer(Player player){ this.player = player; } // ========================= ABSTRACT ======================= /** * Just display the informations of the room on the screen */ public abstract void displayInformation(); /** * Execute the action bind to the room */ public abstract void action(); }
UTF-8
Java
5,808
java
Room.java
Java
[ { "context": ",treasoure and some actions with decor\r\n * @author Loic\r\n * \r\n */\r\n\r\npublic abstract class Room {\r\n\t\r\n\tpr", "end": 553, "score": 0.9922777414321899, "start": 549, "tag": "NAME", "value": "Loic" } ]
null
[]
package dungeon.level; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import dungeon.items.Furniture; import dungeon.commands.CommandFactory; import dungeon.commands.Mod; import dungeon.game.GameBoard; import dungeon.game.Player; import dungeon.items.Item; import dungeon.utils.RandomGenerator; import dungeon.utils.SecureInput; /** * Each elements which composed a level * It contains door(s),monster,treasoure and some actions with decor * @author Loic * */ public abstract class Room { protected Map<Door,Room> neighbours = new HashMap<>(); protected List<Furniture> furnitures; //generate random pllls protected String name; protected Level level; protected boolean isDescribed; private CommandFactory commandFactory; protected Player player = GameBoard.player; /** * construct a room with a name and the level which the room is inside * @param name * @param level */ public Room(String name,Level level){ this.name=name; this.level=level; this.furnitures=RandomGenerator.generateRandomFurnitureList(); } /** * We show to the player all the directions he can go now */ public void displayDirections(){ System.out.println("Possible(s) direction(s) :"); String directions="-- "; Set<Door> listKeys=this.neighbours.keySet(); // key list of the map Iterator<Door> iterateur=listKeys.iterator(); while(iterateur.hasNext()) { Door key= (Door) iterateur.next(); directions+=key.getDirection().toString()+" -- "; } System.out.println(directions); } /** * set a neighbor between two rooms * @param door * @param neighbour */ public void setNeighbour(Door door, Room neighbour){ if(isValidDirection(door.getDirection())) neighbours.put(door,neighbour); } /** * @param direction * @return if the direction not exist in the room */ public boolean isValidDirection(Direction direction){ boolean valid =true; for(Door doorToCompare : this.neighbours.keySet()){ if(doorToCompare.getDirection().equals(direction)) valid=false; } return valid; } /** * @param direction * @return the direction of the player */ public Room goToDirection(Direction direction){ Door door = validDirection(direction,this.neighbours); // test if the direction is possible if(door!=null){ if(door.isLocked()){ if(!this.player.getInventory().isPresent(Item.KEY)){ System.out.println("Sorry you don't have the key to open this door, keep digging around this room"); return null; } else{ this.player.getInventory().useItem(Item.KEY); System.out.println("Good game you have the key to open this door ! You discover a new room !"); } } if(door.isHidden()){ System.out.println("you are a lucky guy you find an hidden door"); } Room nextRoom = neighbours.get(door); //set the neighboor to back in the previous room Direction oppositeDirection=direction.getOppositeDirection(); if(validDirection(oppositeDirection, nextRoom.neighbours)==null){ nextRoom.setNeighbour(new Door(oppositeDirection), this); } return nextRoom; } else return null; } /** * for each Door we look at the direction * @param direction * @param directions * @return */ public Door validDirection(Direction direction,Map<Door, Room> directions){ for(Door door : directions.keySet()){ if(door.getDirection().equals(direction)) return door; } return null; } /** * If the player asks the description of the room : * set the boolean isDescribed to true * display all the objects in the room * show all actions possible with this objects */ public void askDescription(){ this.isDescribed=true; System.out.println("There are in this room : "); if(furnitures.size()==0){ System.out.println("No furniture in this room !"); } else{ for (Furniture furniture : furnitures){ System.out.println("- "+furniture.getFurniture().name()); } this.commandFactory=new CommandFactory(Mod.EXCAVATION_MOD); System.out.println("Now you can examine the furnitures"); examineFurniture(); } } /** * verify if the furniture to examine is correct and call the action associate with it */ public void examineFurniture(){ System.out.println("What do you want to do ? (Enter help to show all the possible commands)"); System.out.print("> "); String line = SecureInput.getNoEmptyStringInput(); String[] cmd = line.split(" ",2); Furniture furniture=null; if(cmd.length!=1 && cmd[0].equals("examine")){ for(Furniture f : furnitures){ if(f.getFurniture().name().equals(cmd[1].toUpperCase())) furniture=f; } if(furniture==null){ System.out.println("Invalid furniture, please try again"); examineFurniture(); } } if(!this.commandFactory.interpretCommand(cmd, this.player, this.level, this,null, furniture)) this.examineFurniture(); } /** * @return the name of the room */ public String getName(){ return this.name; } /** * @return if the player asks the description of the room */ public boolean isDescribed() { return isDescribed; } /** * only used for tests * @param player */ public void setPlayer(Player player){ this.player = player; } // ========================= ABSTRACT ======================= /** * Just display the informations of the room on the screen */ public abstract void displayInformation(); /** * Execute the action bind to the room */ public abstract void action(); }
5,808
0.660296
0.659435
224
23.928572
23.831894
105
false
false
0
0
0
0
0
0
1.964286
false
false
13
de0559f0f5728b438d204aec06013be048103535
11,098,195,526,478
335fef7809e0631838318d73357a1c7890d2c290
/app/src/main/java/com/meowt/wallpapers/InformationActivity.java
bba7db5c9f1ea6ce96b658e1aa03dbce81f49360
[]
no_license
1stApr/MPicture
https://github.com/1stApr/MPicture
1776731e9eac0299f9be4444ff710b9b07f8aec6
8e45fb75311885837dc87e88379ee32269abdeb9
refs/heads/master
2023-01-25T05:19:12.209000
2020-12-07T04:25:49
2020-12-07T04:25:49
197,672,845
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.meowt.wallpapers; import android.annotation.SuppressLint; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.support.annotation.RequiresApi; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.text.method.LinkMovementMethod; import android.view.MenuItem; import android.widget.TextView; import android.widget.Toast; public class InformationActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { private TextView textView12; private TextView textView11; @RequiresApi(api = Build.VERSION_CODES.O) @SuppressLint("WrongViewCast") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_information); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); textView12 = (TextView)findViewById(R.id.textView12); if (textView12 != null) { textView12.setMovementMethod(LinkMovementMethod.getInstance()); } textView11 = (TextView)findViewById(R.id.textView11); if (textView11 != null) { textView11.setMovementMethod(LinkMovementMethod.getInstance()); } DrawerLayout drawer = findViewById(R.id.drawer_layout); NavigationView navigationView = findViewById(R.id.nav_view); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.addDrawerListener(toggle); toggle.syncState(); navigationView.setNavigationItemSelectedListener(this); } @Override public void onBackPressed() { DrawerLayout drawer = findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.nav_home) { Intent intent = new Intent(InformationActivity.this, MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); startActivityIfNeeded(intent, 0); } else if (id == R.id.nav_gallery) { Toast.makeText(getApplicationContext(), "Commingsoon!", Toast.LENGTH_LONG).show(); } else if (id == R.id.nav_featured) { Toast.makeText(getApplicationContext(), "Commingsoon!", Toast.LENGTH_LONG).show(); } else if (id == R.id.nav_contribute) { Intent intent = new Intent(InformationActivity.this, ContributeActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); } else if (id == R.id.nav_donate) { Intent intent = new Intent(InformationActivity.this, DonateActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); } else if (id == R.id.nav_feedback) { Intent intent = new Intent(InformationActivity.this, FeedbackActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); } else if (id == R.id.nav_information) { } DrawerLayout drawer = findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } }
UTF-8
Java
3,849
java
InformationActivity.java
Java
[]
null
[]
package com.meowt.wallpapers; import android.annotation.SuppressLint; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.support.annotation.RequiresApi; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.text.method.LinkMovementMethod; import android.view.MenuItem; import android.widget.TextView; import android.widget.Toast; public class InformationActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { private TextView textView12; private TextView textView11; @RequiresApi(api = Build.VERSION_CODES.O) @SuppressLint("WrongViewCast") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_information); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); textView12 = (TextView)findViewById(R.id.textView12); if (textView12 != null) { textView12.setMovementMethod(LinkMovementMethod.getInstance()); } textView11 = (TextView)findViewById(R.id.textView11); if (textView11 != null) { textView11.setMovementMethod(LinkMovementMethod.getInstance()); } DrawerLayout drawer = findViewById(R.id.drawer_layout); NavigationView navigationView = findViewById(R.id.nav_view); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.addDrawerListener(toggle); toggle.syncState(); navigationView.setNavigationItemSelectedListener(this); } @Override public void onBackPressed() { DrawerLayout drawer = findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.nav_home) { Intent intent = new Intent(InformationActivity.this, MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); startActivityIfNeeded(intent, 0); } else if (id == R.id.nav_gallery) { Toast.makeText(getApplicationContext(), "Commingsoon!", Toast.LENGTH_LONG).show(); } else if (id == R.id.nav_featured) { Toast.makeText(getApplicationContext(), "Commingsoon!", Toast.LENGTH_LONG).show(); } else if (id == R.id.nav_contribute) { Intent intent = new Intent(InformationActivity.this, ContributeActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); } else if (id == R.id.nav_donate) { Intent intent = new Intent(InformationActivity.this, DonateActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); } else if (id == R.id.nav_feedback) { Intent intent = new Intent(InformationActivity.this, FeedbackActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); } else if (id == R.id.nav_information) { } DrawerLayout drawer = findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } }
3,849
0.685633
0.678878
96
39.09375
25.971972
106
false
false
0
0
0
0
0
0
0.6875
false
false
13
0f519dfd7f1a82fbe2ff00f4f08e3372d6779234
27,882,927,751,451
5cb5e4267a3b2bc7d852d1520bdfb6cad0d81827
/src/main/java/com/ail/crxmarkets/model/waterfill/WaterFillMethod.java
63cb4f50914296f61875abe3cea71e90f8d89a60
[]
no_license
ail-man/rainy-hills
https://github.com/ail-man/rainy-hills
0e22ce30c4d94d425e7b22be3a6eff8f4e5f3276
8c8446d754ae226e6d3bd518ad8ac54fcc3a3536
refs/heads/master
2021-01-23T08:15:56.125000
2017-12-14T09:04:19
2017-12-14T09:04:19
86,493,647
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ail.crxmarkets.model.waterfill; /** * Defines an interface of algorithms for calculation of water above the * surface * * @author Arthur Lomsadze (ailman1985@gmail.com) */ public interface WaterFillMethod { /** * Calculates the amount of water above the each point of the surface after * pouring in water and returns as in the form of another array * * @param surface surface array * @param water an array of water available on the surface * @param waterToFill an array of the amount of water that falls on the * surface * @return array of water amount above the each point of the surface */ int[] calcWaterOnSurface(int[] surface, int[] water, int[] waterToFill); }
UTF-8
Java
736
java
WaterFillMethod.java
Java
[ { "context": "lation of water above the\n * surface\n *\n * @author Arthur Lomsadze (ailman1985@gmail.com)\n */\npublic interface Water", "end": 162, "score": 0.9999037384986877, "start": 147, "tag": "NAME", "value": "Arthur Lomsadze" }, { "context": "ove the\n * surface\n *\n * @aut...
null
[]
package com.ail.crxmarkets.model.waterfill; /** * Defines an interface of algorithms for calculation of water above the * surface * * @author <NAME> (<EMAIL>) */ public interface WaterFillMethod { /** * Calculates the amount of water above the each point of the surface after * pouring in water and returns as in the form of another array * * @param surface surface array * @param water an array of water available on the surface * @param waterToFill an array of the amount of water that falls on the * surface * @return array of water amount above the each point of the surface */ int[] calcWaterOnSurface(int[] surface, int[] water, int[] waterToFill); }
714
0.702446
0.697011
23
31
29.648668
76
false
false
0
0
0
0
0
0
0.652174
false
false
13
538d5489d3820f751b18a4a7d0cef84902ac6fd9
29,308,856,896,103
46c4625dcc502a21bef28612cf979f34c4c5b549
/src/pigLatinTranslator.java
14ee4fce4b1da33f533444ac5c1b09b7fae44548
[]
no_license
Airborne4/Nicholas-Lev-1
https://github.com/Airborne4/Nicholas-Lev-1
6a25a4f1ba380957ef87def4d0e837e0b1078afc
eb784412c10268ef0137372713431208e095aa8f
refs/heads/master
2021-01-23T03:44:22.337000
2018-02-03T00:10:20
2018-02-03T00:10:20
86,120,304
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextField; public class pigLatinTranslator implements ActionListener { JFrame j = new JFrame(); JPanel jp = new JPanel(); JTextField answer = new JTextField(20); JButton jb = new JButton("Translate!"); JTextField input = new JTextField(20); public pigLatinTranslator() { j.add(jp); jp.add(input); jp.add(jb); jp.add(answer); j.setVisible(true); j.pack(); jb.setToolTipText("Click to translate!"); j.setDefaultCloseOperation(j.EXIT_ON_CLOSE); answer.setToolTipText("Your translated word!"); input.setToolTipText("Insert word here"); jb.addActionListener(this); } public static void main(String[] args) { new pigLatinTranslator(); } private static boolean isLetter(char c) { return ( (c >='A' && c <='Z') || (c >='a' && c <='z') ); } private static String pigWord(String word) { int split = firstVowel(word); return word.substring(split)+"-"+word.substring(0, split)+"ay"; } public String translate(String s) { String latin = ""; int i = 0; while (i<s.length()) { // Take care of punctuation and spaces while (i<s.length() && !isLetter(s.charAt(i))) { latin = latin + s.charAt(i); i++; } // If there aren't any words left, stop. if (i>=s.length()) break; // Otherwise we're at the beginning of a word. int begin = i; while (i<s.length() && isLetter(s.charAt(i))) { i++; } // Now we're at the end of a word, so translate it. int end = i; latin = latin + pigWord(s.substring(begin, end)); } return latin; } /** * Method to find the index of the first vowel in a word. * @param word The word to search * @return The index of the first vowel */ private static int firstVowel(String word) { word = word.toLowerCase(); for (int i=0; i<word.length(); i++) if (word.charAt(i)=='a' || word.charAt(i)=='e' || word.charAt(i)=='i' || word.charAt(i)=='o' || word.charAt(i)=='u') return i; return 0; } @Override public void actionPerformed(ActionEvent e) { if (e.getSource()==jb) { answer.setText(translate(input.getText())); } } }
UTF-8
Java
2,463
java
pigLatinTranslator.java
Java
[]
null
[]
import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextField; public class pigLatinTranslator implements ActionListener { JFrame j = new JFrame(); JPanel jp = new JPanel(); JTextField answer = new JTextField(20); JButton jb = new JButton("Translate!"); JTextField input = new JTextField(20); public pigLatinTranslator() { j.add(jp); jp.add(input); jp.add(jb); jp.add(answer); j.setVisible(true); j.pack(); jb.setToolTipText("Click to translate!"); j.setDefaultCloseOperation(j.EXIT_ON_CLOSE); answer.setToolTipText("Your translated word!"); input.setToolTipText("Insert word here"); jb.addActionListener(this); } public static void main(String[] args) { new pigLatinTranslator(); } private static boolean isLetter(char c) { return ( (c >='A' && c <='Z') || (c >='a' && c <='z') ); } private static String pigWord(String word) { int split = firstVowel(word); return word.substring(split)+"-"+word.substring(0, split)+"ay"; } public String translate(String s) { String latin = ""; int i = 0; while (i<s.length()) { // Take care of punctuation and spaces while (i<s.length() && !isLetter(s.charAt(i))) { latin = latin + s.charAt(i); i++; } // If there aren't any words left, stop. if (i>=s.length()) break; // Otherwise we're at the beginning of a word. int begin = i; while (i<s.length() && isLetter(s.charAt(i))) { i++; } // Now we're at the end of a word, so translate it. int end = i; latin = latin + pigWord(s.substring(begin, end)); } return latin; } /** * Method to find the index of the first vowel in a word. * @param word The word to search * @return The index of the first vowel */ private static int firstVowel(String word) { word = word.toLowerCase(); for (int i=0; i<word.length(); i++) if (word.charAt(i)=='a' || word.charAt(i)=='e' || word.charAt(i)=='i' || word.charAt(i)=='o' || word.charAt(i)=='u') return i; return 0; } @Override public void actionPerformed(ActionEvent e) { if (e.getSource()==jb) { answer.setText(translate(input.getText())); } } }
2,463
0.588307
0.585059
97
24.226805
20.028591
69
false
false
0
0
0
0
0
0
1.948454
false
false
13
f3483a06bdeea9af343daf6847f439fc23df47b9
395,136,995,965
6923f79f1eaaba0ab28b25337ba6cb56be97d32d
/hadoop_in_practice/src/main/java/com/manning/hip/ch4/joins/contribjoin/Main.java
adc5b3a75fae343a90017dfccc32116efa51d79c
[ "Apache-2.0" ]
permissive
burakbayramli/books
https://github.com/burakbayramli/books
9fe7ba0cabf06e113eb125d62fe16d4946f4a4f0
5e9a0e03aa7ddf5e5ddf89943ccc68d94b539e95
refs/heads/master
2023-08-17T05:31:08.885000
2023-08-14T10:05:37
2023-08-14T10:05:37
72,460,321
223
174
null
false
2022-10-24T12:15:06
2016-10-31T17:24:00
2022-09-24T08:32:06
2022-10-24T07:37:55
757,425
161
152
0
Jupyter Notebook
false
false
package com.manning.hip.ch4.joins.contribjoin; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.*; import org.apache.hadoop.mapred.*; public class Main { public static void main(String... args) throws Exception { JobConf job = new JobConf(); job.setJarByClass(Main.class); String input = args[0]; Path output = new Path(args[1]); output.getFileSystem(job).delete(output, true); job.setMapperClass(Map.class); job.setReducerClass(Reduce.class); job.setMapOutputKeyClass(Text.class); job.setMapOutputValueClass(TextTaggedMapOutput.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(Text.class); FileInputFormat.setInputPaths(job, input); FileOutputFormat.setOutputPath(job, output); JobClient.runJob(job); } }
UTF-8
Java
806
java
Main.java
Java
[]
null
[]
package com.manning.hip.ch4.joins.contribjoin; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.*; import org.apache.hadoop.mapred.*; public class Main { public static void main(String... args) throws Exception { JobConf job = new JobConf(); job.setJarByClass(Main.class); String input = args[0]; Path output = new Path(args[1]); output.getFileSystem(job).delete(output, true); job.setMapperClass(Map.class); job.setReducerClass(Reduce.class); job.setMapOutputKeyClass(Text.class); job.setMapOutputValueClass(TextTaggedMapOutput.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(Text.class); FileInputFormat.setInputPaths(job, input); FileOutputFormat.setOutputPath(job, output); JobClient.runJob(job); } }
806
0.724566
0.720844
31
25
20.038671
60
false
false
0
0
0
0
0
0
0.677419
false
false
13
27578d23da0c241cefb860130ab6c5b93927c49b
15,822,659,532,095
c7a03e45bcca58284619594d7b3951f84d8b2464
/src/game/GameServer.java
65b77e17f319bf1d36eb7693b1c232029326ab2e
[]
no_license
Guardian820/LesGuardians
https://github.com/Guardian820/LesGuardians
02d7098fc01fe71ebed93150b23765f0068db30f
2f30d4ccb2582d78273fa3e3364a09d6b9beffad
refs/heads/master
2021-02-13T19:16:28.232000
2020-03-03T19:19:52
2020-03-03T19:19:52
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package game; import common.Constantes; import common.CryptManager; import common.LesGuardians; import common.SQLManager; import common.SocketManager; import common.World; import game.GameThread; import java.io.IOException; import java.net.ServerSocket; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Timer; import java.util.TimerTask; import objects.Conta; import objects.Maps; import objects.Personagens; import org.fusesource.jansi.AnsiConsole; public class GameServer implements Runnable { private ServerSocket _serverSocket; private Thread _thread; private ArrayList<GameThread> _clientes = new ArrayList(); private ArrayList<Conta> _esperando = new ArrayList(); private Timer _tiempoSalvada; private Timer _subirEstrellas; private Timer _rankingPVP; private Timer _moverPavos; private Timer _publicidad; private long _tiempoInicio; private int _recordJugadores = 0; private String _primeraIp = ""; private String _segundaIp = ""; private String _terceraIp = ""; private int _alterna = 0; private long _tiempoBan1 = 0L; private long _tiempoBan2 = 0L; private boolean _ban = true; private int _i = 0; public GameServer(String Ip) { try { this._tiempoSalvada = new Timer(); this._tiempoSalvada.schedule(new TimerTask(){ @Override public void run() { if (!LesGuardians._salvando) { System.out.println("Servidor salvo em : " + System.currentTimeMillis() + "millisegundos."); Thread t = new Thread(new salvarServidorPersonaje()); t.start(); } else { System.out.println("O servidor est\u00e1 tentando salvar automaticamente, mas o servidor j\u00e1 est\u00e1 salvando (SERVIDOR PERSONAGEM)TIME: " + System.currentTimeMillis()); } } }, LesGuardians.TEMPO_SALVAR, (long)LesGuardians.TEMPO_SALVAR); this._subirEstrellas = new Timer(); this._subirEstrellas.schedule(new TimerTask(){ @Override public void run() { World.subirEstrellasMobs(); } }, LesGuardians.RELOGAR_ESTRELAS_MOBS, (long)LesGuardians.RELOGAR_ESTRELAS_MOBS); this._moverPavos = new Timer(); this._moverPavos.schedule(new TimerTask(){ @Override public void run() { for (Maps.Cercado cercado : World.todosCercados()) { cercado.startMoverDrago(); } } }, LesGuardians.TIEMPO_MOVERSE_PAVOS, (long)LesGuardians.TIEMPO_MOVERSE_PAVOS); this._publicidad = new Timer(); this._publicidad.schedule(new TimerTask(){ @Override public void run() { SocketManager.ENVIAR_Im1223_MENSAJE_IMBORRABLE_TODOS(LesGuardians.PUBLICIDADE.get(GameServer.this._i)); GameServer gameServer = GameServer.this; gameServer._i = gameServer._i + 1; if (GameServer.this._i >= LesGuardians.PUBLICIDADE.size()) { GameServer.this._i = 0; } } }, 3600000L, 3600000L); this._rankingPVP = new Timer(); this._rankingPVP.schedule(new TimerTask(){ @Override public void run() { String antiguoLider = World.liderRanking; Personagens liderViejo = World.getPjPorNombre(antiguoLider); if (liderViejo != null) { liderViejo.setTitulo(0); } SQLManager.ACTUALIZAR_TITULO_POR_NOMBRE(antiguoLider); int idPerso = World.idLiderRankingPVP(); Personagens perso = World.getPersonaje(idPerso); if (perso != null) { perso.setTitulo(8); World.getNPCModelo(1350).configurarNPC(perso.getGfxID(), perso.getSexo(), perso.getColor1(), perso.getColor2(), perso.getColor3(), perso.getStringAccesorios()); } World.liderRanking = World.nombreLiderRankingPVP(); } }, 3600000L, 3600000L); this._serverSocket = new ServerSocket(LesGuardians.PORTA_JOGO); if (LesGuardians.USAR_IP_CRIPTO) { LesGuardians.CRYPTER_IP = String.valueOf(CryptManager.encriptarIP(Ip)) + CryptManager.encriptarPuerto(LesGuardians.PORTA_JOGO); } this._tiempoInicio = System.currentTimeMillis(); this._thread = new Thread(this); this._thread.start(); } catch (IOException e) { System.out.println("IOException: " + e.getMessage()); LesGuardians.cerrarServer(); } } public static void print(String message, int color) { AnsiConsole.out.print("\u001b[" + color + "m" + message + "\u001b[0m"); } public static void clearScreen() { AnsiConsole.out.print("\u001b[H\u001b[2J"); } public static void setTitle(String title) { AnsiConsole.out.printf("%c]0;%s%c", Character.valueOf('\u001b'), title, Character.valueOf('\u0007')); } public ArrayList<GameThread> getClientes() { return this._clientes; } public long getTiempoInicio() { return this._tiempoInicio; } public int getRecordJugadores() { return this._recordJugadores; } public int nroJugadoresLinea() { return this._clientes.size(); } @Override public void run() { while (LesGuardians._corriendo) { try { GameThread gestor = new GameThread(this._serverSocket.accept()); if (LesGuardians.CONTRER_DDOS) { ++this._alterna; String ipTemporal = gestor.getSock().getInetAddress().getHostAddress(); if (!gestor.poderEntrar()) continue; if (this._alterna == 1) { this._primeraIp = ipTemporal; if (this._ban) { this._tiempoBan1 = System.currentTimeMillis(); } else { this._tiempoBan2 = System.currentTimeMillis(); } this._ban = !this._ban; } else if (this._alterna == 2) { this._segundaIp = ipTemporal; if (this._ban) { this._tiempoBan1 = System.currentTimeMillis(); } else { this._tiempoBan2 = System.currentTimeMillis(); } this._ban = !this._ban; } else { this._terceraIp = ipTemporal; this._alterna = 0; if (this._ban) { this._tiempoBan1 = System.currentTimeMillis(); } else { this._tiempoBan2 = System.currentTimeMillis(); } boolean bl = this._ban = !this._ban; } if (this._primeraIp.compareTo(ipTemporal) == 0 && this._segundaIp.compareTo(ipTemporal) == 0 && this._terceraIp.compareTo(ipTemporal) == 0 && Math.abs(this._tiempoBan1 - this._tiempoBan2) < 500L) { Constantes.BAN_IP = String.valueOf(Constantes.BAN_IP) + "," + ipTemporal; SQLManager.INSERT_BANIP(ipTemporal); System.out.println("IP Banido : " + ipTemporal); SocketManager.ENVIAR_Im1223_MENSAJE_IMBORRABLE_TODOS("O IP " + ipTemporal + " foi banido por atacar o servidor."); gestor.getSock().close(); continue; } } ArrayList<GameThread> array = new ArrayList<GameThread>(); array.addAll(this._clientes); for (GameThread EP : array) { if (EP.getCuenta() == null || gestor.getCuenta() == null || gestor.getCuenta().getID() != EP.getCuenta().getID()) continue; EP.salir(); } this._clientes.add(gestor); if (this._clientes.size() <= this._recordJugadores) continue; this._recordJugadores = this._clientes.size(); } catch (IOException e) { System.out.println("IOException: " + e.getMessage()); try { if (!this._serverSocket.isClosed()) { this._serverSocket.close(); } LesGuardians.cerrarServer(); } catch (IOException iOException) { // empty catch block } } } } public void cerrarServidor() { try { this._serverSocket.close(); } catch (IOException iOException) { // empty catch block } ArrayList<GameThread> array = new ArrayList<GameThread>(); array.addAll(this._clientes); for (GameThread EP : array) { try { EP.cerrarSocket(); } catch (Exception exception) { // empty catch block } } } public void delGestorCliente(GameThread entradaPersonaje) { this._clientes.remove(entradaPersonaje); } public synchronized Conta getEsperandoCuenta(int id) { for (int i = 0; i < this._esperando.size(); ++i) { if (this._esperando.get(i).getID() != id) continue; return this._esperando.get(i); } return null; } public synchronized void delEsperandoCuenta(Conta cuenta) { this._esperando.remove(cuenta); } public synchronized void addEsperandoCuenta(Conta cuenta) { this._esperando.add(cuenta); } public static String getTiempoServer() { Date actDate = new Date(); return "BT" + (actDate.getTime() + 3600000L); } public static String getFechaServer() { Date actDate = new Date(); SimpleDateFormat fecha = new SimpleDateFormat("dd"); String dia = String.valueOf(Integer.parseInt(fecha.format(actDate))); while (dia.length() < 2) { dia = "0" + dia; } fecha = new SimpleDateFormat("MM"); String mes = String.valueOf(Integer.parseInt(fecha.format(actDate)) - 1); while (mes.length() < 2) { mes = "0" + mes; } fecha = new SimpleDateFormat("yyyy"); String a\u00f1o = String.valueOf(Integer.parseInt(fecha.format(actDate)) - 1370); return "BD" + a\u00f1o + "|" + mes + "|" + dia; } public Thread getThread() { return this._thread; } public static class salvarServidorPersonaje implements Runnable { @Override public synchronized void run() { if (!LesGuardians._salvando) { SocketManager.ENVIAR_Im_INFORMACION_A_TODOS("1164"); World.salvarServidor(); SocketManager.ENVIAR_Im_INFORMACION_A_TODOS("1165"); } } } }
UTF-8
Java
11,617
java
GameServer.java
Java
[]
null
[]
package game; import common.Constantes; import common.CryptManager; import common.LesGuardians; import common.SQLManager; import common.SocketManager; import common.World; import game.GameThread; import java.io.IOException; import java.net.ServerSocket; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Timer; import java.util.TimerTask; import objects.Conta; import objects.Maps; import objects.Personagens; import org.fusesource.jansi.AnsiConsole; public class GameServer implements Runnable { private ServerSocket _serverSocket; private Thread _thread; private ArrayList<GameThread> _clientes = new ArrayList(); private ArrayList<Conta> _esperando = new ArrayList(); private Timer _tiempoSalvada; private Timer _subirEstrellas; private Timer _rankingPVP; private Timer _moverPavos; private Timer _publicidad; private long _tiempoInicio; private int _recordJugadores = 0; private String _primeraIp = ""; private String _segundaIp = ""; private String _terceraIp = ""; private int _alterna = 0; private long _tiempoBan1 = 0L; private long _tiempoBan2 = 0L; private boolean _ban = true; private int _i = 0; public GameServer(String Ip) { try { this._tiempoSalvada = new Timer(); this._tiempoSalvada.schedule(new TimerTask(){ @Override public void run() { if (!LesGuardians._salvando) { System.out.println("Servidor salvo em : " + System.currentTimeMillis() + "millisegundos."); Thread t = new Thread(new salvarServidorPersonaje()); t.start(); } else { System.out.println("O servidor est\u00e1 tentando salvar automaticamente, mas o servidor j\u00e1 est\u00e1 salvando (SERVIDOR PERSONAGEM)TIME: " + System.currentTimeMillis()); } } }, LesGuardians.TEMPO_SALVAR, (long)LesGuardians.TEMPO_SALVAR); this._subirEstrellas = new Timer(); this._subirEstrellas.schedule(new TimerTask(){ @Override public void run() { World.subirEstrellasMobs(); } }, LesGuardians.RELOGAR_ESTRELAS_MOBS, (long)LesGuardians.RELOGAR_ESTRELAS_MOBS); this._moverPavos = new Timer(); this._moverPavos.schedule(new TimerTask(){ @Override public void run() { for (Maps.Cercado cercado : World.todosCercados()) { cercado.startMoverDrago(); } } }, LesGuardians.TIEMPO_MOVERSE_PAVOS, (long)LesGuardians.TIEMPO_MOVERSE_PAVOS); this._publicidad = new Timer(); this._publicidad.schedule(new TimerTask(){ @Override public void run() { SocketManager.ENVIAR_Im1223_MENSAJE_IMBORRABLE_TODOS(LesGuardians.PUBLICIDADE.get(GameServer.this._i)); GameServer gameServer = GameServer.this; gameServer._i = gameServer._i + 1; if (GameServer.this._i >= LesGuardians.PUBLICIDADE.size()) { GameServer.this._i = 0; } } }, 3600000L, 3600000L); this._rankingPVP = new Timer(); this._rankingPVP.schedule(new TimerTask(){ @Override public void run() { String antiguoLider = World.liderRanking; Personagens liderViejo = World.getPjPorNombre(antiguoLider); if (liderViejo != null) { liderViejo.setTitulo(0); } SQLManager.ACTUALIZAR_TITULO_POR_NOMBRE(antiguoLider); int idPerso = World.idLiderRankingPVP(); Personagens perso = World.getPersonaje(idPerso); if (perso != null) { perso.setTitulo(8); World.getNPCModelo(1350).configurarNPC(perso.getGfxID(), perso.getSexo(), perso.getColor1(), perso.getColor2(), perso.getColor3(), perso.getStringAccesorios()); } World.liderRanking = World.nombreLiderRankingPVP(); } }, 3600000L, 3600000L); this._serverSocket = new ServerSocket(LesGuardians.PORTA_JOGO); if (LesGuardians.USAR_IP_CRIPTO) { LesGuardians.CRYPTER_IP = String.valueOf(CryptManager.encriptarIP(Ip)) + CryptManager.encriptarPuerto(LesGuardians.PORTA_JOGO); } this._tiempoInicio = System.currentTimeMillis(); this._thread = new Thread(this); this._thread.start(); } catch (IOException e) { System.out.println("IOException: " + e.getMessage()); LesGuardians.cerrarServer(); } } public static void print(String message, int color) { AnsiConsole.out.print("\u001b[" + color + "m" + message + "\u001b[0m"); } public static void clearScreen() { AnsiConsole.out.print("\u001b[H\u001b[2J"); } public static void setTitle(String title) { AnsiConsole.out.printf("%c]0;%s%c", Character.valueOf('\u001b'), title, Character.valueOf('\u0007')); } public ArrayList<GameThread> getClientes() { return this._clientes; } public long getTiempoInicio() { return this._tiempoInicio; } public int getRecordJugadores() { return this._recordJugadores; } public int nroJugadoresLinea() { return this._clientes.size(); } @Override public void run() { while (LesGuardians._corriendo) { try { GameThread gestor = new GameThread(this._serverSocket.accept()); if (LesGuardians.CONTRER_DDOS) { ++this._alterna; String ipTemporal = gestor.getSock().getInetAddress().getHostAddress(); if (!gestor.poderEntrar()) continue; if (this._alterna == 1) { this._primeraIp = ipTemporal; if (this._ban) { this._tiempoBan1 = System.currentTimeMillis(); } else { this._tiempoBan2 = System.currentTimeMillis(); } this._ban = !this._ban; } else if (this._alterna == 2) { this._segundaIp = ipTemporal; if (this._ban) { this._tiempoBan1 = System.currentTimeMillis(); } else { this._tiempoBan2 = System.currentTimeMillis(); } this._ban = !this._ban; } else { this._terceraIp = ipTemporal; this._alterna = 0; if (this._ban) { this._tiempoBan1 = System.currentTimeMillis(); } else { this._tiempoBan2 = System.currentTimeMillis(); } boolean bl = this._ban = !this._ban; } if (this._primeraIp.compareTo(ipTemporal) == 0 && this._segundaIp.compareTo(ipTemporal) == 0 && this._terceraIp.compareTo(ipTemporal) == 0 && Math.abs(this._tiempoBan1 - this._tiempoBan2) < 500L) { Constantes.BAN_IP = String.valueOf(Constantes.BAN_IP) + "," + ipTemporal; SQLManager.INSERT_BANIP(ipTemporal); System.out.println("IP Banido : " + ipTemporal); SocketManager.ENVIAR_Im1223_MENSAJE_IMBORRABLE_TODOS("O IP " + ipTemporal + " foi banido por atacar o servidor."); gestor.getSock().close(); continue; } } ArrayList<GameThread> array = new ArrayList<GameThread>(); array.addAll(this._clientes); for (GameThread EP : array) { if (EP.getCuenta() == null || gestor.getCuenta() == null || gestor.getCuenta().getID() != EP.getCuenta().getID()) continue; EP.salir(); } this._clientes.add(gestor); if (this._clientes.size() <= this._recordJugadores) continue; this._recordJugadores = this._clientes.size(); } catch (IOException e) { System.out.println("IOException: " + e.getMessage()); try { if (!this._serverSocket.isClosed()) { this._serverSocket.close(); } LesGuardians.cerrarServer(); } catch (IOException iOException) { // empty catch block } } } } public void cerrarServidor() { try { this._serverSocket.close(); } catch (IOException iOException) { // empty catch block } ArrayList<GameThread> array = new ArrayList<GameThread>(); array.addAll(this._clientes); for (GameThread EP : array) { try { EP.cerrarSocket(); } catch (Exception exception) { // empty catch block } } } public void delGestorCliente(GameThread entradaPersonaje) { this._clientes.remove(entradaPersonaje); } public synchronized Conta getEsperandoCuenta(int id) { for (int i = 0; i < this._esperando.size(); ++i) { if (this._esperando.get(i).getID() != id) continue; return this._esperando.get(i); } return null; } public synchronized void delEsperandoCuenta(Conta cuenta) { this._esperando.remove(cuenta); } public synchronized void addEsperandoCuenta(Conta cuenta) { this._esperando.add(cuenta); } public static String getTiempoServer() { Date actDate = new Date(); return "BT" + (actDate.getTime() + 3600000L); } public static String getFechaServer() { Date actDate = new Date(); SimpleDateFormat fecha = new SimpleDateFormat("dd"); String dia = String.valueOf(Integer.parseInt(fecha.format(actDate))); while (dia.length() < 2) { dia = "0" + dia; } fecha = new SimpleDateFormat("MM"); String mes = String.valueOf(Integer.parseInt(fecha.format(actDate)) - 1); while (mes.length() < 2) { mes = "0" + mes; } fecha = new SimpleDateFormat("yyyy"); String a\u00f1o = String.valueOf(Integer.parseInt(fecha.format(actDate)) - 1370); return "BD" + a\u00f1o + "|" + mes + "|" + dia; } public Thread getThread() { return this._thread; } public static class salvarServidorPersonaje implements Runnable { @Override public synchronized void run() { if (!LesGuardians._salvando) { SocketManager.ENVIAR_Im_INFORMACION_A_TODOS("1164"); World.salvarServidor(); SocketManager.ENVIAR_Im_INFORMACION_A_TODOS("1165"); } } } }
11,617
0.530343
0.518895
298
37.979866
30.745975
217
false
false
0
0
0
0
0
0
0.57047
false
false
13
20accace6a8b840f329bebc0b3e14653e48019aa
4,226,247,839,141
28ce0cdee7aed073c67a58fa2765f0b11f112e6c
/modules/web/src/com/company/testaddandcreatenew/web/screens/child/ChildEdit.java
5e042af63ff6d58854ccc898a714b1a8e7e71386
[]
no_license
alexbudarov/cubasaveandnew
https://github.com/alexbudarov/cubasaveandnew
eb89bc17111d35571200a14dbaf06ad3d29bc1fe
f53c560a2140e4f97ea27be457879b86c89bec5e
refs/heads/main
2023-02-26T07:45:12.506000
2021-02-05T16:25:02
2021-02-05T16:25:02
336,325,614
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.company.testaddandcreatenew.web.screens.child; import com.company.testaddandcreatenew.entity.Parent; import com.haulmont.cuba.core.entity.Entity; import com.haulmont.cuba.core.global.Messages; import com.haulmont.cuba.core.global.MetadataTools; import com.haulmont.cuba.gui.Notifications; import com.haulmont.cuba.gui.components.Action; import com.haulmont.cuba.gui.model.DataContext; import com.haulmont.cuba.gui.screen.*; import com.company.testaddandcreatenew.entity.Child; import javax.inject.Inject; import java.util.ArrayList; import java.util.List; @UiController("testaddandcreatenew_Child.edit") @UiDescriptor("child-edit.xml") @EditedEntityContainer("childDc") @LoadDataBeforeShow public class ChildEdit extends StandardEditor<Child> { @Inject private Notifications notifications; @Inject private DataContext dataContext; private final List<Child> additionalNewEntities = new ArrayList<>(); private Parent parentEntity; @Subscribe("saveAndNew") public void onSaveAndNew(Action.ActionPerformedEvent event) { if (validateScreen().isEmpty()) { commitChanges() .then(() -> { // commented // commitActionPerformed = true; if (showSaveNotification) { Entity entity = getEditedEntity(); MetadataTools metadataTools = getBeanLocator().get(MetadataTools.NAME); Messages messages = getBeanLocator().get(Messages.NAME); notifications.create(Notifications.NotificationType.TRAY) .withCaption(messages.formatMainMessage("info.EntitySave", messages.getTools().getEntityCaption(entity.getMetaClass()), metadataTools.getInstanceName(entity))) .show(); } // remember committed entities before last one additionalNewEntities.add(getEditedEntity()); // create new item, set as edited entity Child newItem = dataContext.create(Child.class); newItem.setParent(parentEntity); getEditedEntityContainer().setItem(newItem); // to prevent "unsaved changes" setModifiedAfterOpen(false); }); } } public List<Child> getAdditionalNewEntities() { return additionalNewEntities; } public void setParentEntity(Parent parentEntity) { this.parentEntity = parentEntity; } }
UTF-8
Java
2,766
java
ChildEdit.java
Java
[]
null
[]
package com.company.testaddandcreatenew.web.screens.child; import com.company.testaddandcreatenew.entity.Parent; import com.haulmont.cuba.core.entity.Entity; import com.haulmont.cuba.core.global.Messages; import com.haulmont.cuba.core.global.MetadataTools; import com.haulmont.cuba.gui.Notifications; import com.haulmont.cuba.gui.components.Action; import com.haulmont.cuba.gui.model.DataContext; import com.haulmont.cuba.gui.screen.*; import com.company.testaddandcreatenew.entity.Child; import javax.inject.Inject; import java.util.ArrayList; import java.util.List; @UiController("testaddandcreatenew_Child.edit") @UiDescriptor("child-edit.xml") @EditedEntityContainer("childDc") @LoadDataBeforeShow public class ChildEdit extends StandardEditor<Child> { @Inject private Notifications notifications; @Inject private DataContext dataContext; private final List<Child> additionalNewEntities = new ArrayList<>(); private Parent parentEntity; @Subscribe("saveAndNew") public void onSaveAndNew(Action.ActionPerformedEvent event) { if (validateScreen().isEmpty()) { commitChanges() .then(() -> { // commented // commitActionPerformed = true; if (showSaveNotification) { Entity entity = getEditedEntity(); MetadataTools metadataTools = getBeanLocator().get(MetadataTools.NAME); Messages messages = getBeanLocator().get(Messages.NAME); notifications.create(Notifications.NotificationType.TRAY) .withCaption(messages.formatMainMessage("info.EntitySave", messages.getTools().getEntityCaption(entity.getMetaClass()), metadataTools.getInstanceName(entity))) .show(); } // remember committed entities before last one additionalNewEntities.add(getEditedEntity()); // create new item, set as edited entity Child newItem = dataContext.create(Child.class); newItem.setParent(parentEntity); getEditedEntityContainer().setItem(newItem); // to prevent "unsaved changes" setModifiedAfterOpen(false); }); } } public List<Child> getAdditionalNewEntities() { return additionalNewEntities; } public void setParentEntity(Parent parentEntity) { this.parentEntity = parentEntity; } }
2,766
0.604121
0.604121
72
37.430557
27.749287
104
false
false
0
0
0
0
0
0
0.458333
false
false
13
b54be2e9b513ed4e8d70209d61eba7d653425e3e
2,181,843,408,636
8a450feec777ab92aac935185a879059c6828c0a
/src/main/java/servlet/dish/DishChangeNum.java
17fc86384257242e2281e6c544f8d0988cb8a924
[]
no_license
skyyemperor/canteen
https://github.com/skyyemperor/canteen
052f22632040ecb928d9767e2feccb37156d39a2
ebb9c7e0f49e86a18d5ff9e247bd64c303a472d0
refs/heads/master
2021-06-21T19:41:50.974000
2019-12-06T14:44:26
2019-12-06T14:44:26
225,318,061
2
0
null
false
2021-06-04T02:21:24
2019-12-02T08:00:43
2021-02-02T06:06:22
2021-06-04T02:21:23
36
0
0
3
Java
false
false
package servlet.dish; import com.alibaba.fastjson.JSON; import dao.DishDao; import entity.Dish; import util.Info; import util.MSG; 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 java.io.IOException; import java.io.PrintWriter; @WebServlet("/dishChangeNum") public class DishChangeNum extends HttpServlet { private String NAME = "name"; private String FLAG = "flag"; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //设置请求编码 request.setCharacterEncoding("UTF-8"); Info info = null; boolean bool = false; int flag = -1; try { String dish_name = ""; if (request.getParameter(NAME) != null) { dish_name = request.getParameter(NAME); } if (request.getParameter(FLAG)!=null){ flag=Integer.parseInt(request.getParameter(FLAG)); } Dish dish = DishDao.selectByName(dish_name); if (flag==1){ bool=DishDao.addNiceNum(dish); }else if (flag==2){ bool=DishDao.reduceNiceNum(dish); }else if (flag==3){ bool=DishDao.addBadNum(dish); }else if (flag==4){ bool=DishDao.reduceBadNum(dish); } Dish dish1 = DishDao.selectByName(dish_name); if (bool) { info = new Info(0,MSG.SUCCESS,dish1); } else { info = new Info(-1, MSG.SQL_ERROR); } String dishes = JSON.toJSONString(info); response.setCharacterEncoding("UTF-8"); response.setContentType("application/json"); response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "PUT, GET, POST, DELETE, OPTIONS"); response.setHeader("Access-Control-Allow-Credentials", "true"); response.setHeader("Access-Control-Allow-Headers", "x-requested-with,content-type,accept,token"); PrintWriter out = response.getWriter(); out.write(dishes); out.flush(); } catch (Exception e) { e.printStackTrace(); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } }
UTF-8
Java
2,620
java
DishChangeNum.java
Java
[]
null
[]
package servlet.dish; import com.alibaba.fastjson.JSON; import dao.DishDao; import entity.Dish; import util.Info; import util.MSG; 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 java.io.IOException; import java.io.PrintWriter; @WebServlet("/dishChangeNum") public class DishChangeNum extends HttpServlet { private String NAME = "name"; private String FLAG = "flag"; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //设置请求编码 request.setCharacterEncoding("UTF-8"); Info info = null; boolean bool = false; int flag = -1; try { String dish_name = ""; if (request.getParameter(NAME) != null) { dish_name = request.getParameter(NAME); } if (request.getParameter(FLAG)!=null){ flag=Integer.parseInt(request.getParameter(FLAG)); } Dish dish = DishDao.selectByName(dish_name); if (flag==1){ bool=DishDao.addNiceNum(dish); }else if (flag==2){ bool=DishDao.reduceNiceNum(dish); }else if (flag==3){ bool=DishDao.addBadNum(dish); }else if (flag==4){ bool=DishDao.reduceBadNum(dish); } Dish dish1 = DishDao.selectByName(dish_name); if (bool) { info = new Info(0,MSG.SUCCESS,dish1); } else { info = new Info(-1, MSG.SQL_ERROR); } String dishes = JSON.toJSONString(info); response.setCharacterEncoding("UTF-8"); response.setContentType("application/json"); response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "PUT, GET, POST, DELETE, OPTIONS"); response.setHeader("Access-Control-Allow-Credentials", "true"); response.setHeader("Access-Control-Allow-Headers", "x-requested-with,content-type,accept,token"); PrintWriter out = response.getWriter(); out.write(dishes); out.flush(); } catch (Exception e) { e.printStackTrace(); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } }
2,620
0.608512
0.604294
76
33.315788
26.927393
122
false
false
0
0
0
0
0
0
0.802632
false
false
13
5cfad8d601de1da187f822fda847d4fad2bd729b
6,047,313,992,759
9e4b806cbecf275c313d4d0fbe7a4862db5398f9
/src/main/java/ru/job4j/tracker/Tracker.java
a3c17b79530aad7d40db9c03dff0521767ac0b99
[]
no_license
Snower87/job4j_tracker2
https://github.com/Snower87/job4j_tracker2
1d23e2f1d2ed9baf72a22f7c1a0a97e5413aa5c0
795795639ee405600a45919a30bc9585bf00f434
refs/heads/master
2022-11-21T17:27:03.882000
2020-07-23T10:41:50
2020-07-23T10:41:50
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ru.job4j.tracker; import java.sql.Array; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; /** /* Class Tracker описывает бизнес-модель заявки, 1) базовый код для хранилища tracker * 2) добавлен метод замены replace заявки по ключу id 3) добавлен метод удаления заявки delete * 4) добавлена проверка входн. пар-ов в методы (валидация) 5) убрал переопределение методов: equals, hashcode * 6) Переход от массива Item[] items -> к List<Item> 7) коррекция в методе findByName * @author Sergei Begletsov * @since 02.06.2020 * @version 7 */ public class Tracker { private final List<Item> items = new ArrayList<>(); private int ids = 1; /** * Метод добавления заявки в хранилище * @param item новая заявка */ public Item add(Item item) { item.setId(generateId()); items.add(item); return item; } /** * Метод добавления заявки в хранилище * @param id номер заявки */ private int indexOf(String id) { int rsl = -1; for (int index = 0; index < items.size(); index++) { if (items.get(index).getId().equals(id)) { rsl = index; break; } } return rsl; } /** * Метод поиска всех не нулевых заявок в хранилище */ public List<Item> findAll() { return items; } /** * Метод поиска заявки в хранилище по ключу * @param key номер заявки */ public List<Item> findByName(String key) { List<Item> copyItems = new ArrayList<>(); for (int index = 0; index < items.size(); index++) { Item item = this.items.get(index); if (key.equals(item.getName())) { copyItems.add(this.items.get(index)); } } return copyItems; } /** * Метод поиска заявки в хранилище * @param id номер заявки */ public Item findById(String id) { // Находим индекс int index = indexOf(id); // Если индекс найден возвращаем item, иначе null return index != -1 ? items.get(index) : null; } /** * Метод генерирует номер id */ private String generateId() { return String.valueOf(ids++); } /** * Метод замены старого итема на новый по номеру id (ключу) * @param id номер заявки * @param item новый итем * @return true - замена успешно прошла, false - не произошла */ public boolean replace(String id, Item item) { //1. Находим индекс ячейки по id int index = indexOf(id); //2. Валидация. Проверка входных пар-ов boolean res = index != -1; // Если индекс найден, то меняю заявку if (res) { //3. Сохраняю старый id заявки item.setId(id); //4. Записываю в найденную ячейку объект item items.set(index, item); } return res; } /** * Метод удаления итема по номеру id * @param id номер заявки * @return true - удаление прошло успешно, false - не произошло */ public boolean delete(String id) { //1. Находим индекс удаляемой ячейки по id int index = indexOf(id); //2. Валидация. Проверка входных пар-ов boolean res = index != -1; // Если индекс найден, удаляю элемент со сдвигом if (res) { items.remove(index); } return res; } }
UTF-8
Java
4,370
java
Tracker.java
Java
[ { "context": "<Item> 7) коррекция в методе findByName\n * @author Sergei Begletsov\n * @since 02.06.2020\n * @version 7\n */\n\npublic cl", "end": 566, "score": 0.9998445510864258, "start": 550, "tag": "NAME", "value": "Sergei Begletsov" } ]
null
[]
package ru.job4j.tracker; import java.sql.Array; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; /** /* Class Tracker описывает бизнес-модель заявки, 1) базовый код для хранилища tracker * 2) добавлен метод замены replace заявки по ключу id 3) добавлен метод удаления заявки delete * 4) добавлена проверка входн. пар-ов в методы (валидация) 5) убрал переопределение методов: equals, hashcode * 6) Переход от массива Item[] items -> к List<Item> 7) коррекция в методе findByName * @author <NAME> * @since 02.06.2020 * @version 7 */ public class Tracker { private final List<Item> items = new ArrayList<>(); private int ids = 1; /** * Метод добавления заявки в хранилище * @param item новая заявка */ public Item add(Item item) { item.setId(generateId()); items.add(item); return item; } /** * Метод добавления заявки в хранилище * @param id номер заявки */ private int indexOf(String id) { int rsl = -1; for (int index = 0; index < items.size(); index++) { if (items.get(index).getId().equals(id)) { rsl = index; break; } } return rsl; } /** * Метод поиска всех не нулевых заявок в хранилище */ public List<Item> findAll() { return items; } /** * Метод поиска заявки в хранилище по ключу * @param key номер заявки */ public List<Item> findByName(String key) { List<Item> copyItems = new ArrayList<>(); for (int index = 0; index < items.size(); index++) { Item item = this.items.get(index); if (key.equals(item.getName())) { copyItems.add(this.items.get(index)); } } return copyItems; } /** * Метод поиска заявки в хранилище * @param id номер заявки */ public Item findById(String id) { // Находим индекс int index = indexOf(id); // Если индекс найден возвращаем item, иначе null return index != -1 ? items.get(index) : null; } /** * Метод генерирует номер id */ private String generateId() { return String.valueOf(ids++); } /** * Метод замены старого итема на новый по номеру id (ключу) * @param id номер заявки * @param item новый итем * @return true - замена успешно прошла, false - не произошла */ public boolean replace(String id, Item item) { //1. Находим индекс ячейки по id int index = indexOf(id); //2. Валидация. Проверка входных пар-ов boolean res = index != -1; // Если индекс найден, то меняю заявку if (res) { //3. Сохраняю старый id заявки item.setId(id); //4. Записываю в найденную ячейку объект item items.set(index, item); } return res; } /** * Метод удаления итема по номеру id * @param id номер заявки * @return true - удаление прошло успешно, false - не произошло */ public boolean delete(String id) { //1. Находим индекс удаляемой ячейки по id int index = indexOf(id); //2. Валидация. Проверка входных пар-ов boolean res = index != -1; // Если индекс найден, удаляю элемент со сдвигом if (res) { items.remove(index); } return res; } }
4,360
0.573878
0.565304
125
27
21.942835
110
false
false
0
0
0
0
0
0
0.36
false
false
13
b5249b0e3e8a1c2803a670a3bce21089b7c2cc3d
3,693,671,882,738
1100b55d796f912707de65b24f9740e51688f8cd
/app/src/main/java/com/example/mienhv1/survey/ui/adapter/OnUpdateListener.java
898deb3359b2d095f8f031fb9222cc282d466c58
[]
no_license
hvmien/survey-md
https://github.com/hvmien/survey-md
722e09b9a15caa7221227cbea01fd7e38072a497
7c8499e0d9d99408e92371c7516a9a0be527245f
refs/heads/master
2021-01-19T11:04:12.371000
2017-12-05T13:24:19
2017-12-05T13:24:19
87,923,802
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.mienhv1.survey.ui.adapter; import java.util.ArrayList; /** * Created by Forev on 17/04/21. */ public interface OnUpdateListener<T> { void onUpdate(ArrayList<T> data); }
UTF-8
Java
197
java
OnUpdateListener.java
Java
[ { "context": "r;\n\nimport java.util.ArrayList;\n\n/**\n * Created by Forev on 17/04/21.\n */\n\npublic interface OnUpdateListen", "end": 100, "score": 0.6875499486923218, "start": 95, "tag": "USERNAME", "value": "Forev" } ]
null
[]
package com.example.mienhv1.survey.ui.adapter; import java.util.ArrayList; /** * Created by Forev on 17/04/21. */ public interface OnUpdateListener<T> { void onUpdate(ArrayList<T> data); }
197
0.720812
0.685279
12
15.5
17.490473
46
false
false
0
0
0
0
0
0
0.25
false
false
13
245b8c85ca6087f3e6e098b3ec3a5a0768d09133
16,724,602,655,975
bf1a911223ad9fc72621500a438d40d24066dec8
/src/LoadTimeTable.java
c24f2e01c70ab9023f92d9775ad3a8aea1d3d37b
[]
no_license
jiaekim123/gong-gang-finder
https://github.com/jiaekim123/gong-gang-finder
b95468c227d771fc6db0c5e5c89f51941064e42d
6ee8d27400af76d810fac77167bb49880b22cc9c
refs/heads/master
2022-02-26T04:48:02.110000
2019-10-03T08:11:13
2019-10-03T08:14:23
212,526,063
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.emptytimefinder; import java.util.ArrayList; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.graphics.Color; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; public class LoadTimeTable extends Activity implements AdapterView.OnItemSelectedListener, OnClickListener { ArrayList<String> itemlist, tablelist, namelist, nametablelist, schedulelist; //팀 이름 list,팀전체의 시간표 list, 팀원이름 list,해당이름일때의시간표 list, 스케줄 list ArrayList<Integer> indexlist, numberlist; //선택된 index기억하는 list, 팀플스케줄이 있는 index 저장 String dbName = "gteamDB.db"; // 데이터베이스의 이름; String tableName1 = "gteamTBL"; // 이름이 저장된 table String tableIndex = "", str = " ", myitem; // 시간표가 저장될 str, 해당시간에수업인사람 str, 현재선택item int dbMode = Context.MODE_PRIVATE; int howtime_count=0, number, i, namecount = 0, tablecount = 0; //몇명이 수업인지 int[] num; int[] ischecked = new int[35]; FrameLayout TimeTableLayout, BottomLayout; //Gridlayout, 아래 textView TextView name, myText, WhatTime, WhoTime,MiddleText; //gridview맨위에text,현재텍스트,ㅇ요일ㅇ시간,누가듣는지,설명 Button LoadTeam_btn, CheckOK_btn, Comeback_Btn;//시간표확인버튼,gridlayout에서 돌아오는확인버튼,시간표만들기로 돌아가기 Button[] LoadButtons = new Button[35]; Integer[] loadBtnIDs = { R.id.r2c1, R.id.r2c2, R.id.r2c3, R.id.r2c4, R.id.r2c5, R.id.r3c1, R.id.r3c2, R.id.r3c3, R.id.r3c4, R.id.r3c5, R.id.r4c1, R.id.r4c2, R.id.r4c3, R.id.r4c4, R.id.r4c5, R.id.r5c1, R.id.r5c2, R.id.r5c3, R.id.r5c4, R.id.r5c5, R.id.r6c1, R.id.r6c2, R.id.r6c3, R.id.r6c4, R.id.r6c5, R.id.r7c1, R.id.r7c2, R.id.r7c3, R.id.r7c4, R.id.r7c5, R.id.r8c1, R.id.r8c2, R.id.r8c3, R.id.r8c4, R.id.r8c5 }; SQLiteDatabase sqlDB; // sqlDB = openOrCreateDatabase(dbName, dbMode, null); /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.load_timetable_layout); // TODO Auto-generated method stub BottomLayout = (FrameLayout) findViewById(R.id.bottom_layout); TimeTableLayout = (FrameLayout) findViewById(R.id.time_table); LoadTeam_btn = (Button) findViewById(R.id.load_team_button); CheckOK_btn = (Button) findViewById(R.id.check_timetable); Comeback_Btn = (Button) findViewById(R.id.come_back_button); name = (TextView) findViewById(R.id.timetable_name); myText = (TextView) findViewById(R.id.mytext); WhatTime = (TextView) findViewById(R.id.what_time); WhoTime = (TextView) findViewById(R.id.who_time); MiddleText = (TextView) findViewById(R.id.middle_text); sqlDB = openOrCreateDatabase(dbName, dbMode, null); itemlist = new ArrayList<String>(); tablelist = new ArrayList<String>(); namelist = new ArrayList<String>(); nametablelist = new ArrayList<String>(); schedulelist = new ArrayList<String>(); indexlist = new ArrayList<Integer>(); numberlist = new ArrayList<Integer>(); // 스피터 객체 참조 Spinner checkspin = (Spinner) findViewById(R.id.load_spinner); checkspin.setOnItemSelectedListener(this); // 어댑터 객체 생성 getMyTeam(); ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, itemlist); adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); checkspin.setAdapter(adapter2); for (i = 0; i < loadBtnIDs.length; i++) { LoadButtons[i] = (Button) findViewById(loadBtnIDs[i]); } for (i = 0; i < loadBtnIDs.length; i++) { final int index; index = i; LoadButtons[i].setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { BottomLayout.setVisibility(View.VISIBLE);//아래 TextView 보이게 viewWeek(index); //ㅇ요일ㅇ교시인지 설정 getMyname(myitem); //현재 선택된 이름을 가져옴 findWhoTime(index); //현재 선택된 index에 수업이 누구인지 설정 MiddleText.setText("수업인 사람:"); if(howtime_count==0){ //공강일경우(아무도 수업이 아닐경우) setNumber(index); //현재 인덱스 설정 if(numberlist.contains(index)){ //스케줄에 이 인덱스가 등록되어있을때 setschedulelist(); //스케줄 설정 int scheduleNum = numberlist.indexOf(index); //번호 가져옴 String scheduleStr; //스케줄 String생성 scheduleStr = schedulelist.get(scheduleNum); //스케줄 내용을 가져옴 WhoTime.setText(scheduleStr);//스케줄 내용으로 TextView 설정 MiddleText.setText("팀플스케줄 : "); //WhoTime.setText(schedulelist.get(0)); }else{ getDialog(); //스케줄을 생성하겠냐는 다이얼로그를 띄움 } } schedulelist.clear(); //스케줄리스트 클리어 howtime_count = 0; //몇명이 수업인지 클리어 } }); } TimeTableLayout.setVisibility(View.INVISIBLE); BottomLayout.setVisibility(View.INVISIBLE); LoadTeam_btn.setOnClickListener(this); CheckOK_btn.setOnClickListener(this); Comeback_Btn.setOnClickListener(this); tableColorReset(); } @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { myitem = itemlist.get(position); // Toast.makeText(LoadTimeTable.this,itemlist.get(position) + // "을 선택 했습니다.", 1).show(); } @Override public void onNothingSelected(AdapterView<?> parent) { // TODO Auto-generated method stub } public void getMyTeam() { Cursor cursor; cursor = sqlDB.rawQuery("SELECT * FROM gteamTBL;", null); while (cursor.moveToNext()) { itemlist.add(cursor.getString(0)); } cursor.close(); } public void setData(){ Cursor cursor; int number = getNumber(); cursor = sqlDB.rawQuery( "select schedule from scheduleTable where number = '" + number + "';", null); while (cursor.moveToNext()) { WhoTime.setText(cursor.getString(0)); Log.e("tablecount", Integer.toString(tablecount)); } cursor.close(); // sqlDB.close(); } public void getDialog(){ AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("일정등록") .setIcon(R.drawable.ic_launcher) .setMessage("일정을 등록하시겠습니까?") .setPositiveButton("예",new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub dialog.cancel(); getCustomDialog(); } }) .setNegativeButton("아니오", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub dialog.cancel(); } }).show(); } public void getCustomDialog(){ Context mContext = getApplicationContext(); LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE); View layout = inflater.inflate(R.layout.custom_dialog,(ViewGroup)findViewById(R.id.layout_dialog)); AlertDialog.Builder aDialog = new AlertDialog.Builder(LoadTimeTable.this); aDialog.setTitle("스케줄 등록"); aDialog.setIcon(R.drawable.ic_launcher); aDialog.setView(layout); final EditText Edt_schedule = new EditText(mContext); aDialog.setView(Edt_schedule); Edt_schedule.setTextColor(Color.BLACK); aDialog.setPositiveButton("등록하기", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub //setSchedule(edt_schedule.getText().toString()); setSchedule(Edt_schedule.getText().toString()); setData(); dialog.cancel(); } }); aDialog.setNegativeButton("취소", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub dialog.cancel(); } }); AlertDialog ad = aDialog.create(); ad.show(); } public void setNumber(int index){ number = index; } public int getNumber(){ return number; } public void setSchedule(String schedule){ Toast.makeText(getApplicationContext(),schedule,1).show(); int number = getNumber(); String sql = "insert into scheduleTable values('" + number + "','" + schedule + "');"; sqlDB.execSQL(sql); LoadButtons[number].setBackgroundColor(Color.parseColor("#ff0000")); } public void selectSchedule(){ Cursor cursor; cursor = sqlDB.rawQuery("select number from scheduleTable;", null); while (cursor.moveToNext()) { numberlist.add(Integer.parseInt(cursor.getString(0))); } cursor.close(); for(int i=0;i<numberlist.size();i++){ LoadButtons[numberlist.get(i)].setBackgroundColor(Color.parseColor("#ff0000")); } } public void setschedulelist(){ Cursor cursor; cursor = sqlDB.rawQuery("select schedule from scheduleTable;", null); while (cursor.moveToNext()) { schedulelist.add(cursor.getString(0)); } cursor.close(); } public void getMytable(String team) { Cursor cursor; cursor = sqlDB.rawQuery( "select timetable from teamTimeTable where team = '" + team + "';", null); tablecount = 0; while (cursor.moveToNext()) { tablelist.add(cursor.getString(0)); tablecount++; Log.e("tablecount", Integer.toString(tablecount)); } cursor.close(); // sqlDB.close(); } public void getMyname(String team) { Cursor cursor; cursor = sqlDB.rawQuery("select name from teamTimeTable where team = '" + team + "';", null); namecount = 0; while (cursor.moveToNext()) { namelist.add(cursor.getString(0)); namecount++; Log.e("namecount", Integer.toString(namecount)); } cursor.close(); // sqlDB.close(); } public void findWhoTime(int index) {//누가 이 시간에 수업이니1!!! for (int i = 0; i < namelist.size(); i++) { Cursor cursor; cursor = sqlDB.rawQuery( "select timetable from teamTimeTable where name = '" + namelist.get(i) + "';", null); //일단 이 팀에있는애들 시간표 내놔! while (cursor.moveToNext()) {//다음사람도 다내놔!! nametablelist.add(cursor.getString(0));//이 이름인애들 시간표 다 넣어!! } cursor.close(); for (int count = 0; count < nametablelist.size(); count++) {//시간표수만큼반복 String[] array = nametablelist.get(count).split(",");//시간표분리해서 array에 넣음 //시간표가 (11,22,32,1,3,2,)이런식으로 저장되있어서 index만 떼올라고 split해줌 for (int j = 0; j < array.length; j++) {//array길이만큼 반복 indexlist.add(Integer.parseInt(array[j])); //array안에 있는걸 indexlist에 넣음 array[j]="";//array는 다시 비움 } } nametablelist.clear();//이 팀에 있는 애들 시간표도 비움 if (indexlist.contains(index)) { //이 시간에 너 수업듣니?? str += namelist.get(i) + " "; // 이름이 뭐니?? howtime_count++; //수업듣는사람이 한명 늘었구나. } indexlist.clear(); //저장된 시간표 index 초기화 } WhoTime.setText(str);//누가 듣는지 출력 namelist.clear(); //팀에 있는 애들 이름 초기화 str="";//누가 듣는지 출렸햇으니까 너도 초기화 } public void tableColorReset() { for (i = 0; i < loadBtnIDs.length; i++) { LoadButtons[i].setBackgroundColor(Color.parseColor("#00FF00")); selectSchedule(); } } public void viewWeek(int index) { if ((index % 5) == 0) {// 월요일 WhatTime.setText("월요일 " + ((index / 5) + 1) + "교시"); } else if ((index % 5) == 1) {// 화요일 WhatTime.setText("화요일 " + (((index - 1) / 5) + 1) + "교시"); } else if ((index % 5) == 2) {// 수요일 WhatTime.setText("수요일 " + (((index - 2) / 5) + 1) + "교시"); } else if ((index % 5) == 3) { WhatTime.setText("목요일 " + (((index - 3) / 5) + 1) + "교시"); } else {// 금요일 WhatTime.setText("금요일 " + (((index - 4) / 5) + 1) + "교시"); } } public void setEmptytimetable(){ for (int count = 0; count < tablecount; count++) { Log.e("count", Integer.toString(count)); String[] array = tablelist.get(count).split(","); num = new int[1000]; for (int j = 0; j < array.length; j++) { num[j] = Integer.parseInt(array[j]); } for (i = 0; i < loadBtnIDs.length; i++) { if ((num[i] % 2) == 0) { LoadButtons[num[i]].setBackgroundColor(Color .parseColor("#888888")); } else { LoadButtons[num[i]].setBackgroundColor(Color .parseColor("#808080")); } } } } @Override public void onClick(View v) { // TODO Auto-generated method stub switch (v.getId()) { case R.id.load_team_button: TimeTableLayout.setVisibility(View.VISIBLE); name.setText(myitem); myText.setText(myitem + "팀 공강시간표입니다.(초록색 : 공강)"); getMytable(myitem); CheckOK_btn.setText("확인"); setEmptytimetable(); break; case R.id.check_timetable: tableColorReset(); TimeTableLayout.setVisibility(View.INVISIBLE); BottomLayout.setVisibility(View.INVISIBLE); break; case R.id.come_back_button: Intent mIntent_comeback = new Intent(LoadTimeTable.this, MakeTimeTable.class); startActivity(mIntent_comeback); break; } } }
UHC
Java
13,975
java
LoadTimeTable.java
Java
[]
null
[]
package com.example.emptytimefinder; import java.util.ArrayList; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.graphics.Color; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; public class LoadTimeTable extends Activity implements AdapterView.OnItemSelectedListener, OnClickListener { ArrayList<String> itemlist, tablelist, namelist, nametablelist, schedulelist; //팀 이름 list,팀전체의 시간표 list, 팀원이름 list,해당이름일때의시간표 list, 스케줄 list ArrayList<Integer> indexlist, numberlist; //선택된 index기억하는 list, 팀플스케줄이 있는 index 저장 String dbName = "gteamDB.db"; // 데이터베이스의 이름; String tableName1 = "gteamTBL"; // 이름이 저장된 table String tableIndex = "", str = " ", myitem; // 시간표가 저장될 str, 해당시간에수업인사람 str, 현재선택item int dbMode = Context.MODE_PRIVATE; int howtime_count=0, number, i, namecount = 0, tablecount = 0; //몇명이 수업인지 int[] num; int[] ischecked = new int[35]; FrameLayout TimeTableLayout, BottomLayout; //Gridlayout, 아래 textView TextView name, myText, WhatTime, WhoTime,MiddleText; //gridview맨위에text,현재텍스트,ㅇ요일ㅇ시간,누가듣는지,설명 Button LoadTeam_btn, CheckOK_btn, Comeback_Btn;//시간표확인버튼,gridlayout에서 돌아오는확인버튼,시간표만들기로 돌아가기 Button[] LoadButtons = new Button[35]; Integer[] loadBtnIDs = { R.id.r2c1, R.id.r2c2, R.id.r2c3, R.id.r2c4, R.id.r2c5, R.id.r3c1, R.id.r3c2, R.id.r3c3, R.id.r3c4, R.id.r3c5, R.id.r4c1, R.id.r4c2, R.id.r4c3, R.id.r4c4, R.id.r4c5, R.id.r5c1, R.id.r5c2, R.id.r5c3, R.id.r5c4, R.id.r5c5, R.id.r6c1, R.id.r6c2, R.id.r6c3, R.id.r6c4, R.id.r6c5, R.id.r7c1, R.id.r7c2, R.id.r7c3, R.id.r7c4, R.id.r7c5, R.id.r8c1, R.id.r8c2, R.id.r8c3, R.id.r8c4, R.id.r8c5 }; SQLiteDatabase sqlDB; // sqlDB = openOrCreateDatabase(dbName, dbMode, null); /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.load_timetable_layout); // TODO Auto-generated method stub BottomLayout = (FrameLayout) findViewById(R.id.bottom_layout); TimeTableLayout = (FrameLayout) findViewById(R.id.time_table); LoadTeam_btn = (Button) findViewById(R.id.load_team_button); CheckOK_btn = (Button) findViewById(R.id.check_timetable); Comeback_Btn = (Button) findViewById(R.id.come_back_button); name = (TextView) findViewById(R.id.timetable_name); myText = (TextView) findViewById(R.id.mytext); WhatTime = (TextView) findViewById(R.id.what_time); WhoTime = (TextView) findViewById(R.id.who_time); MiddleText = (TextView) findViewById(R.id.middle_text); sqlDB = openOrCreateDatabase(dbName, dbMode, null); itemlist = new ArrayList<String>(); tablelist = new ArrayList<String>(); namelist = new ArrayList<String>(); nametablelist = new ArrayList<String>(); schedulelist = new ArrayList<String>(); indexlist = new ArrayList<Integer>(); numberlist = new ArrayList<Integer>(); // 스피터 객체 참조 Spinner checkspin = (Spinner) findViewById(R.id.load_spinner); checkspin.setOnItemSelectedListener(this); // 어댑터 객체 생성 getMyTeam(); ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, itemlist); adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); checkspin.setAdapter(adapter2); for (i = 0; i < loadBtnIDs.length; i++) { LoadButtons[i] = (Button) findViewById(loadBtnIDs[i]); } for (i = 0; i < loadBtnIDs.length; i++) { final int index; index = i; LoadButtons[i].setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { BottomLayout.setVisibility(View.VISIBLE);//아래 TextView 보이게 viewWeek(index); //ㅇ요일ㅇ교시인지 설정 getMyname(myitem); //현재 선택된 이름을 가져옴 findWhoTime(index); //현재 선택된 index에 수업이 누구인지 설정 MiddleText.setText("수업인 사람:"); if(howtime_count==0){ //공강일경우(아무도 수업이 아닐경우) setNumber(index); //현재 인덱스 설정 if(numberlist.contains(index)){ //스케줄에 이 인덱스가 등록되어있을때 setschedulelist(); //스케줄 설정 int scheduleNum = numberlist.indexOf(index); //번호 가져옴 String scheduleStr; //스케줄 String생성 scheduleStr = schedulelist.get(scheduleNum); //스케줄 내용을 가져옴 WhoTime.setText(scheduleStr);//스케줄 내용으로 TextView 설정 MiddleText.setText("팀플스케줄 : "); //WhoTime.setText(schedulelist.get(0)); }else{ getDialog(); //스케줄을 생성하겠냐는 다이얼로그를 띄움 } } schedulelist.clear(); //스케줄리스트 클리어 howtime_count = 0; //몇명이 수업인지 클리어 } }); } TimeTableLayout.setVisibility(View.INVISIBLE); BottomLayout.setVisibility(View.INVISIBLE); LoadTeam_btn.setOnClickListener(this); CheckOK_btn.setOnClickListener(this); Comeback_Btn.setOnClickListener(this); tableColorReset(); } @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { myitem = itemlist.get(position); // Toast.makeText(LoadTimeTable.this,itemlist.get(position) + // "을 선택 했습니다.", 1).show(); } @Override public void onNothingSelected(AdapterView<?> parent) { // TODO Auto-generated method stub } public void getMyTeam() { Cursor cursor; cursor = sqlDB.rawQuery("SELECT * FROM gteamTBL;", null); while (cursor.moveToNext()) { itemlist.add(cursor.getString(0)); } cursor.close(); } public void setData(){ Cursor cursor; int number = getNumber(); cursor = sqlDB.rawQuery( "select schedule from scheduleTable where number = '" + number + "';", null); while (cursor.moveToNext()) { WhoTime.setText(cursor.getString(0)); Log.e("tablecount", Integer.toString(tablecount)); } cursor.close(); // sqlDB.close(); } public void getDialog(){ AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("일정등록") .setIcon(R.drawable.ic_launcher) .setMessage("일정을 등록하시겠습니까?") .setPositiveButton("예",new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub dialog.cancel(); getCustomDialog(); } }) .setNegativeButton("아니오", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub dialog.cancel(); } }).show(); } public void getCustomDialog(){ Context mContext = getApplicationContext(); LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE); View layout = inflater.inflate(R.layout.custom_dialog,(ViewGroup)findViewById(R.id.layout_dialog)); AlertDialog.Builder aDialog = new AlertDialog.Builder(LoadTimeTable.this); aDialog.setTitle("스케줄 등록"); aDialog.setIcon(R.drawable.ic_launcher); aDialog.setView(layout); final EditText Edt_schedule = new EditText(mContext); aDialog.setView(Edt_schedule); Edt_schedule.setTextColor(Color.BLACK); aDialog.setPositiveButton("등록하기", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub //setSchedule(edt_schedule.getText().toString()); setSchedule(Edt_schedule.getText().toString()); setData(); dialog.cancel(); } }); aDialog.setNegativeButton("취소", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub dialog.cancel(); } }); AlertDialog ad = aDialog.create(); ad.show(); } public void setNumber(int index){ number = index; } public int getNumber(){ return number; } public void setSchedule(String schedule){ Toast.makeText(getApplicationContext(),schedule,1).show(); int number = getNumber(); String sql = "insert into scheduleTable values('" + number + "','" + schedule + "');"; sqlDB.execSQL(sql); LoadButtons[number].setBackgroundColor(Color.parseColor("#ff0000")); } public void selectSchedule(){ Cursor cursor; cursor = sqlDB.rawQuery("select number from scheduleTable;", null); while (cursor.moveToNext()) { numberlist.add(Integer.parseInt(cursor.getString(0))); } cursor.close(); for(int i=0;i<numberlist.size();i++){ LoadButtons[numberlist.get(i)].setBackgroundColor(Color.parseColor("#ff0000")); } } public void setschedulelist(){ Cursor cursor; cursor = sqlDB.rawQuery("select schedule from scheduleTable;", null); while (cursor.moveToNext()) { schedulelist.add(cursor.getString(0)); } cursor.close(); } public void getMytable(String team) { Cursor cursor; cursor = sqlDB.rawQuery( "select timetable from teamTimeTable where team = '" + team + "';", null); tablecount = 0; while (cursor.moveToNext()) { tablelist.add(cursor.getString(0)); tablecount++; Log.e("tablecount", Integer.toString(tablecount)); } cursor.close(); // sqlDB.close(); } public void getMyname(String team) { Cursor cursor; cursor = sqlDB.rawQuery("select name from teamTimeTable where team = '" + team + "';", null); namecount = 0; while (cursor.moveToNext()) { namelist.add(cursor.getString(0)); namecount++; Log.e("namecount", Integer.toString(namecount)); } cursor.close(); // sqlDB.close(); } public void findWhoTime(int index) {//누가 이 시간에 수업이니1!!! for (int i = 0; i < namelist.size(); i++) { Cursor cursor; cursor = sqlDB.rawQuery( "select timetable from teamTimeTable where name = '" + namelist.get(i) + "';", null); //일단 이 팀에있는애들 시간표 내놔! while (cursor.moveToNext()) {//다음사람도 다내놔!! nametablelist.add(cursor.getString(0));//이 이름인애들 시간표 다 넣어!! } cursor.close(); for (int count = 0; count < nametablelist.size(); count++) {//시간표수만큼반복 String[] array = nametablelist.get(count).split(",");//시간표분리해서 array에 넣음 //시간표가 (11,22,32,1,3,2,)이런식으로 저장되있어서 index만 떼올라고 split해줌 for (int j = 0; j < array.length; j++) {//array길이만큼 반복 indexlist.add(Integer.parseInt(array[j])); //array안에 있는걸 indexlist에 넣음 array[j]="";//array는 다시 비움 } } nametablelist.clear();//이 팀에 있는 애들 시간표도 비움 if (indexlist.contains(index)) { //이 시간에 너 수업듣니?? str += namelist.get(i) + " "; // 이름이 뭐니?? howtime_count++; //수업듣는사람이 한명 늘었구나. } indexlist.clear(); //저장된 시간표 index 초기화 } WhoTime.setText(str);//누가 듣는지 출력 namelist.clear(); //팀에 있는 애들 이름 초기화 str="";//누가 듣는지 출렸햇으니까 너도 초기화 } public void tableColorReset() { for (i = 0; i < loadBtnIDs.length; i++) { LoadButtons[i].setBackgroundColor(Color.parseColor("#00FF00")); selectSchedule(); } } public void viewWeek(int index) { if ((index % 5) == 0) {// 월요일 WhatTime.setText("월요일 " + ((index / 5) + 1) + "교시"); } else if ((index % 5) == 1) {// 화요일 WhatTime.setText("화요일 " + (((index - 1) / 5) + 1) + "교시"); } else if ((index % 5) == 2) {// 수요일 WhatTime.setText("수요일 " + (((index - 2) / 5) + 1) + "교시"); } else if ((index % 5) == 3) { WhatTime.setText("목요일 " + (((index - 3) / 5) + 1) + "교시"); } else {// 금요일 WhatTime.setText("금요일 " + (((index - 4) / 5) + 1) + "교시"); } } public void setEmptytimetable(){ for (int count = 0; count < tablecount; count++) { Log.e("count", Integer.toString(count)); String[] array = tablelist.get(count).split(","); num = new int[1000]; for (int j = 0; j < array.length; j++) { num[j] = Integer.parseInt(array[j]); } for (i = 0; i < loadBtnIDs.length; i++) { if ((num[i] % 2) == 0) { LoadButtons[num[i]].setBackgroundColor(Color .parseColor("#888888")); } else { LoadButtons[num[i]].setBackgroundColor(Color .parseColor("#808080")); } } } } @Override public void onClick(View v) { // TODO Auto-generated method stub switch (v.getId()) { case R.id.load_team_button: TimeTableLayout.setVisibility(View.VISIBLE); name.setText(myitem); myText.setText(myitem + "팀 공강시간표입니다.(초록색 : 공강)"); getMytable(myitem); CheckOK_btn.setText("확인"); setEmptytimetable(); break; case R.id.check_timetable: tableColorReset(); TimeTableLayout.setVisibility(View.INVISIBLE); BottomLayout.setVisibility(View.INVISIBLE); break; case R.id.come_back_button: Intent mIntent_comeback = new Intent(LoadTimeTable.this, MakeTimeTable.class); startActivity(mIntent_comeback); break; } } }
13,975
0.682369
0.669323
387
32.077518
22.911564
101
false
false
0
0
0
0
0
0
3.129199
false
false
13
23bdc11f6082618d78a748ee227ca00f1cb21351
22,007,412,429,997
5665d2e2df84463e0b96714fce7fa64573fe57c2
/app/src/main/java/com/rnergachev/giph/data/network/response/RandomResponse.java
863629f3f5ca976cb84b17bc589a26013749fa21
[]
no_license
romannergachev/giph
https://github.com/romannergachev/giph
efd05d7d55b292303c589594241f2278e5e0cb9c
593f62bd2dd8bb7017c9f6373de2750355fcf440
refs/heads/master
2021-01-18T17:42:30.787000
2017-08-23T14:06:39
2017-08-23T14:06:39
100,495,257
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.rnergachev.giph.data.network.response; import com.rnergachev.giph.data.model.RandomGiphData; /** * Retrofit Random response */ public class RandomResponse { private RandomGiphData data; public RandomResponse() { } public RandomResponse(RandomGiphData data) { this.data = data; } public RandomGiphData getData() { return data; } }
UTF-8
Java
394
java
RandomResponse.java
Java
[]
null
[]
package com.rnergachev.giph.data.network.response; import com.rnergachev.giph.data.model.RandomGiphData; /** * Retrofit Random response */ public class RandomResponse { private RandomGiphData data; public RandomResponse() { } public RandomResponse(RandomGiphData data) { this.data = data; } public RandomGiphData getData() { return data; } }
394
0.680203
0.680203
22
16.90909
18.148151
53
false
false
0
0
0
0
0
0
0.227273
false
false
13
651f9bca0ea8b82ec95e84673f5f30113fb409ec
23,776,938,957,235
c2c3a97a83afd0446339c9b0fbd3d0fd387808b9
/src/main/java/at/renehollander/duktape/value/primitive/DukUndefined.java
6ba0acbd5c35aae8d711ca2639ef7ee95cb2acb8
[ "MIT" ]
permissive
dant3/duktape-java
https://github.com/dant3/duktape-java
7fd891610aeccd43977961994720ae96dc012a4a
dac19023c00590e146cf9c7b385412a66cd0748b
refs/heads/master
2021-01-15T13:35:12.755000
2015-08-27T16:48:24
2015-08-27T16:48:24
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package at.renehollander.duktape.value.primitive; import at.renehollander.duktape.Duktape; import at.renehollander.duktape.value.AbstractDukValue; public final class DukUndefined extends AbstractDukValue { public DukUndefined(Duktape parent) { super(parent); } @Override public boolean isUndefined() { return true; } @Override public DukUndefined asUndefined() { return this; } @Override public String toString() { return "undefined"; } @Override public boolean equals(Object obj) { return obj instanceof DukUndefined; } @Override public int hashCode() { return 1; } }
UTF-8
Java
693
java
DukUndefined.java
Java
[]
null
[]
package at.renehollander.duktape.value.primitive; import at.renehollander.duktape.Duktape; import at.renehollander.duktape.value.AbstractDukValue; public final class DukUndefined extends AbstractDukValue { public DukUndefined(Duktape parent) { super(parent); } @Override public boolean isUndefined() { return true; } @Override public DukUndefined asUndefined() { return this; } @Override public String toString() { return "undefined"; } @Override public boolean equals(Object obj) { return obj instanceof DukUndefined; } @Override public int hashCode() { return 1; } }
693
0.650794
0.649351
36
18.25
17.523596
58
false
false
0
0
0
0
0
0
0.25
false
false
13
221e557f897a7d62b4f9ef7e1ec423d64cdc610a
23,776,938,955,944
2a94229fd967dae8b4fb66dad9b1a24aad8c97b5
/SkyApplication/app/src/main/java/com/sky/app/ui/activity/shop/CardActivity.java
a42da6c66b6a67207d46c4e5c44d809b77231092
[]
no_license
syuanlj/syrepository
https://github.com/syuanlj/syrepository
893682f915086042cf33dbe39b59f376355de5cf
765e4c76f49d27692bd476ea0133001ee2e41630
refs/heads/master
2021-09-07T19:52:42.830000
2018-01-10T08:32:53
2018-01-10T08:32:53
104,959,439
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sky.app.ui.activity.shop; import android.content.Intent; import android.os.Bundle; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.Toolbar; import android.text.TextUtils; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; import com.sky.app.R; import com.sky.app.bean.CollectPubIn; import com.sky.app.bean.CommentRequest; import com.sky.app.bean.CommentResponse; import com.sky.app.bean.ProductIntroduceIn; import com.sky.app.bean.ProductIntroduceOut; import com.sky.app.contract.SellerContract; import com.sky.app.contract.ShopContract; import com.sky.app.library.base.ui.BaseViewActivity; import com.sky.app.library.component.RecycleViewDivider; import com.sky.app.library.component.recycler.interfaces.OnLoadMoreListener; import com.sky.app.library.component.recycler.recyclerview.LuRecyclerView; import com.sky.app.library.component.recycler.recyclerview.LuRecyclerViewAdapter; import com.sky.app.library.utils.AppUtils; import com.sky.app.library.utils.DialogUtils; import com.sky.app.library.utils.ImageHelper; import com.sky.app.library.utils.T; import com.sky.app.presenter.AllCommentPresenter; import com.sky.app.presenter.CollectPresenter; import com.sky.app.presenter.shop.CardPresenter; import com.sky.app.ui.activity.baidumap.BaiduMapActivity; import com.sky.app.ui.activity.order.CommentActivity; import com.sky.app.ui.adapter.AllCommentAdaptor; import com.sky.app.utils.ShareUtils; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.OnClick; /** * 个人名片 */ public class CardActivity extends BaseViewActivity<SellerContract.ICardPresenter> implements SellerContract.ICardView, ShopContract.ICollectionView, ShopContract.IAllCommentView, SwipeRefreshLayout.OnRefreshListener{ @BindView(R.id.normal_toolbar) Toolbar toolbar; @BindView(R.id.app_title) TextView title; @BindView(R.id.app_swipe) SwipeRefreshLayout mSwipeRefreshLayout; @BindView(R.id.app_comment_list) LuRecyclerView mRecyclerView; AllCommentAdaptor allCommentAdaptor; List<CommentResponse> commentResponses = new ArrayList<>(); private LuRecyclerViewAdapter mLuRecyclerViewAdapter = null; private CommentRequest commentRequest = new CommentRequest(); private String seller_id; private ProductIntroduceOut productIntroduceOut; @BindView(R.id.comment_type) RadioGroup radioGroup; private ShopContract.ICollectionPresenter iCollectionPresenter; private ShopContract.IAllCommentPresenter iAllCommentPresenter; @BindView(R.id.app_collect) TextView collect; @BindView(R.id.app_icon) ImageView appIcon; @BindView(R.id.app_user_name) TextView userName; @BindView(R.id.app_time) TextView appTime; @BindView(R.id.app_main_sell) TextView mainSell; @BindView(R.id.shop_collect) Button collectBtn; @BindView(R.id.navigate) LinearLayout navigate; @BindView(R.id.all) RadioButton allBtn; @BindView(R.id.has_pic) RadioButton picBtn; // // @BindView(R.id.qq) // TextView qq; // @BindView(R.id.weixin) // TextView weixin; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.app_card); } @Override protected SellerContract.ICardPresenter presenter() { iCollectionPresenter = new CollectPresenter(context, this); iAllCommentPresenter = new AllCommentPresenter(context, this); return new CardPresenter(context, this); } @Override protected void initViewsAndEvents() { toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()){ case R.id.app_share: ShareUtils.share(CardActivity.this, "", "", ""); break; } return false; } }); mRecyclerView.setLayoutManager(new LinearLayoutManager(context)); mRecyclerView.setHasFixedSize(true); mRecyclerView.addItemDecoration(new RecycleViewDivider(context, LinearLayoutManager.HORIZONTAL, AppUtils.dip2px(context, 1), AppUtils.getSystemColor(context, R.color.sky_color_f2f2f2))); allCommentAdaptor = new AllCommentAdaptor(context, commentResponses); mLuRecyclerViewAdapter = new LuRecyclerViewAdapter(allCommentAdaptor); mRecyclerView.setAdapter(mLuRecyclerViewAdapter); mRecyclerView.setOnLoadMoreListener(new OnLoadMoreListener() { @Override public void onLoadMore() { if (iAllCommentPresenter.hasMore()){ loadData(); } else { mRecyclerView.setNoMore(true); } } }); //设置底部加载颜色 mRecyclerView.setFooterViewColor(R.color.main_colorAccent, R.color.main_colorAccent ,android.R.color.white); //设置底部加载文字提示 mRecyclerView.setFooterViewHint("拼命加载中", "已经全部加载完", "网络不给力啊,点击再试一次吧"); onRefresh(); //请求个人主页信息 ProductIntroduceIn productIntroduceIn = new ProductIntroduceIn(); productIntroduceIn.setUser_id(seller_id); getPresenter().requestCardInfo(productIntroduceIn); //查询评论数量 searchCommentNum(); } @Override protected void init() { title.setText(R.string.app_card_string); toolbar.setNavigationIcon(R.mipmap.app_back_arrow_icon); toolbar.inflateMenu(R.menu.app_share_menu); //设置刷新时动画的颜色,可以设置4个 if (mSwipeRefreshLayout != null) { mSwipeRefreshLayout.setProgressViewOffset(false, 0, AppUtils.dip2px(context, 48)); mSwipeRefreshLayout.setColorSchemeResources(R.color.main_colorPrimary); mSwipeRefreshLayout.setOnRefreshListener(this); } seller_id = getIntent().getStringExtra("seller_id"); commentRequest.setType(1);//商户编号 commentRequest.setValue(seller_id); radioGroup.check(R.id.all); } @Override public void showError(String error) { super.showError(error); T.showShort(context, error); mSwipeRefreshLayout.setRefreshing(false); } @Override protected void onDestoryActivity() { } @Override public void showCollectView(String msg) { T.showShort(context, msg); switch (tag){ case 1: collectBtn.setText("收藏"); break; case 2: collectBtn.setText("已收藏"); break; case 3: collect.setText("收藏"); AppUtils.changeTextViewIcon(context, collect, R.mipmap.app_product_detail_star_icon, 2); break; case 4: collect.setText("已收藏"); AppUtils.changeTextViewIcon(context, collect, R.mipmap.app_product_detail_selected_star_icon, 2); break; } } @Override public void showCollectError(String error) { T.showShort(context, error); switch (tag){ case 1: collectBtn.setText("已收藏"); break; case 2: collectBtn.setText("收藏"); break; case 3: collect.setText("已收藏"); AppUtils.changeTextViewIcon(context, collect, R.mipmap.app_product_detail_selected_star_icon, 2); break; case 4: collect.setText("收藏"); AppUtils.changeTextViewIcon(context, collect, R.mipmap.app_product_detail_star_icon, 2); break; } } @Override public void getRefreshData(List<CommentResponse> list, int tag, int num) { switch (tag){ case 1: allBtn.setText("全部(" + num + ")"); break; case 2: picBtn.setText("有图(" + num + ")"); break; } allCommentAdaptor.add(list); if(mSwipeRefreshLayout.isRefreshing()){ mSwipeRefreshLayout.setRefreshing(false); } mRecyclerView.refreshComplete(20); mLuRecyclerViewAdapter.notifyDataSetChanged(); } @Override public void getLoadMoreData(List<CommentResponse> list, int tag, int num) { switch (tag){ case 1: allBtn.setText("全部(" + num + ")"); break; case 2: picBtn.setText("有图(" + num + ")"); break; } allCommentAdaptor.addAll(list); mSwipeRefreshLayout.setRefreshing(false); mRecyclerView.refreshComplete(20); mLuRecyclerViewAdapter.notifyDataSetChanged(); } @Override public void onRefresh() { mSwipeRefreshLayout.setRefreshing(true); mRecyclerView.setRefreshing(true); refresh(); } @OnClick({R.id.all, R.id.has_pic}) void clickSelectPic(RadioButton radioButton){ switch (radioButton.getId()){ case R.id.all: commentRequest.setPic_type(""); onRefresh(); break; case R.id.has_pic: commentRequest.setPic_type("1"); onRefresh(); break; } } @OnClick({R.id.navigate}) void turnToMap(){ Intent intent=new Intent(this, BaiduMapActivity.class); startActivity(intent); } @OnClick(R.id.app_call_phone) void call(){ if (null == productIntroduceOut || TextUtils.isEmpty(productIntroduceOut.getMobile())){ T.showShort(context, "找不到号码"); return; } AppUtils.callPhone(context, productIntroduceOut.getMobile()); } private int tag = -1; @OnClick(R.id.app_collect) void clickCollect(){ CollectPubIn collectPubIn = new CollectPubIn(); collectPubIn.setType("2"); collectPubIn.setCollect_value(seller_id); if ("已收藏".equals(collect.getText().toString())){ iCollectionPresenter.cancelCollect(collectPubIn); tag = 3; } else { tag = 4; iCollectionPresenter.requestCollect(collectPubIn); } } @OnClick(R.id.shop_collect) void collect(){ CollectPubIn collectPubIn = new CollectPubIn(); collectPubIn.setType("2"); collectPubIn.setCollect_value(seller_id); if ("已收藏".equals(collectBtn.getText().toString())){ tag = 1; iCollectionPresenter.cancelCollect(collectPubIn); } else { tag = 2; iCollectionPresenter.requestCollect(collectPubIn); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); ShareUtils.onActivityResult(this, requestCode, resultCode, data); } @Override public void responseCardInfo(ProductIntroduceOut productIntroduceOut) { this.productIntroduceOut = productIntroduceOut; ImageHelper.getInstance().displayDefinedImage(productIntroduceOut.getPic_url(), appIcon, R.mipmap.app_default_icon, R.mipmap.app_default_icon); userName.setText(productIntroduceOut.getNick_name()); appTime.setText("从业时间:" + (TextUtils.isEmpty(productIntroduceOut.getWorktime()) ? "" : productIntroduceOut.getWorktime())); mainSell.setText("主营业务:" + (TextUtils.isEmpty(productIntroduceOut.getMain_business_desc()) ? "" : productIntroduceOut.getMain_business_desc())); if (1 == productIntroduceOut.getIs_collect()){ collect.setText("已收藏"); AppUtils.changeTextViewIcon(context, collect, R.mipmap.app_product_detail_selected_star_icon, 2); collectBtn.setText("已收藏"); }else{ collect.setText("收藏"); collectBtn.setText("收藏"); AppUtils.changeTextViewIcon(context, collect, R.mipmap.app_product_detail_star_icon, 2); } // qq.setText(productIntroduceOut.getQq()); // weixin.setText(productIntroduceOut.getWeixin()); } /** * 刷新数据 */ private void refresh(){ if (TextUtils.isEmpty(commentRequest.getPic_type())){ iAllCommentPresenter.loadData(commentRequest, 1); }else{ iAllCommentPresenter.loadData(commentRequest, 2); } } /** * 加载数据 */ private void loadData(){ if (TextUtils.isEmpty(commentRequest.getPic_type())) { iAllCommentPresenter.loadMore(commentRequest, 1); }else{ iAllCommentPresenter.loadMore(commentRequest, 2); } } /** * 搜索评论数量 */ private void searchCommentNum() { iAllCommentPresenter.requestAllCommentNum(commentRequest); } @Override public void responseAllCommentNum(int all) { allBtn.setText("全部(" + all + ")"); } @Override public void responsePicNum(int pic) { picBtn.setText("有图(" + pic + ")"); } @Override public void showProgress() { super.showProgress(); DialogUtils.showLoading(this); } @Override public void hideProgress() { super.hideProgress(); DialogUtils.hideLoading(); } @OnClick(R.id.publish_comment) void skipComment(){ Intent r = new Intent(context, CommentActivity.class); r.putExtra("image", productIntroduceOut.getPic_url()); r.putExtra("type", 1);//0 订单 1 商户 r.putExtra("about_user_id", seller_id); startActivity(r); } }
UTF-8
Java
14,588
java
CardActivity.java
Java
[]
null
[]
package com.sky.app.ui.activity.shop; import android.content.Intent; import android.os.Bundle; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.Toolbar; import android.text.TextUtils; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; import com.sky.app.R; import com.sky.app.bean.CollectPubIn; import com.sky.app.bean.CommentRequest; import com.sky.app.bean.CommentResponse; import com.sky.app.bean.ProductIntroduceIn; import com.sky.app.bean.ProductIntroduceOut; import com.sky.app.contract.SellerContract; import com.sky.app.contract.ShopContract; import com.sky.app.library.base.ui.BaseViewActivity; import com.sky.app.library.component.RecycleViewDivider; import com.sky.app.library.component.recycler.interfaces.OnLoadMoreListener; import com.sky.app.library.component.recycler.recyclerview.LuRecyclerView; import com.sky.app.library.component.recycler.recyclerview.LuRecyclerViewAdapter; import com.sky.app.library.utils.AppUtils; import com.sky.app.library.utils.DialogUtils; import com.sky.app.library.utils.ImageHelper; import com.sky.app.library.utils.T; import com.sky.app.presenter.AllCommentPresenter; import com.sky.app.presenter.CollectPresenter; import com.sky.app.presenter.shop.CardPresenter; import com.sky.app.ui.activity.baidumap.BaiduMapActivity; import com.sky.app.ui.activity.order.CommentActivity; import com.sky.app.ui.adapter.AllCommentAdaptor; import com.sky.app.utils.ShareUtils; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.OnClick; /** * 个人名片 */ public class CardActivity extends BaseViewActivity<SellerContract.ICardPresenter> implements SellerContract.ICardView, ShopContract.ICollectionView, ShopContract.IAllCommentView, SwipeRefreshLayout.OnRefreshListener{ @BindView(R.id.normal_toolbar) Toolbar toolbar; @BindView(R.id.app_title) TextView title; @BindView(R.id.app_swipe) SwipeRefreshLayout mSwipeRefreshLayout; @BindView(R.id.app_comment_list) LuRecyclerView mRecyclerView; AllCommentAdaptor allCommentAdaptor; List<CommentResponse> commentResponses = new ArrayList<>(); private LuRecyclerViewAdapter mLuRecyclerViewAdapter = null; private CommentRequest commentRequest = new CommentRequest(); private String seller_id; private ProductIntroduceOut productIntroduceOut; @BindView(R.id.comment_type) RadioGroup radioGroup; private ShopContract.ICollectionPresenter iCollectionPresenter; private ShopContract.IAllCommentPresenter iAllCommentPresenter; @BindView(R.id.app_collect) TextView collect; @BindView(R.id.app_icon) ImageView appIcon; @BindView(R.id.app_user_name) TextView userName; @BindView(R.id.app_time) TextView appTime; @BindView(R.id.app_main_sell) TextView mainSell; @BindView(R.id.shop_collect) Button collectBtn; @BindView(R.id.navigate) LinearLayout navigate; @BindView(R.id.all) RadioButton allBtn; @BindView(R.id.has_pic) RadioButton picBtn; // // @BindView(R.id.qq) // TextView qq; // @BindView(R.id.weixin) // TextView weixin; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.app_card); } @Override protected SellerContract.ICardPresenter presenter() { iCollectionPresenter = new CollectPresenter(context, this); iAllCommentPresenter = new AllCommentPresenter(context, this); return new CardPresenter(context, this); } @Override protected void initViewsAndEvents() { toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()){ case R.id.app_share: ShareUtils.share(CardActivity.this, "", "", ""); break; } return false; } }); mRecyclerView.setLayoutManager(new LinearLayoutManager(context)); mRecyclerView.setHasFixedSize(true); mRecyclerView.addItemDecoration(new RecycleViewDivider(context, LinearLayoutManager.HORIZONTAL, AppUtils.dip2px(context, 1), AppUtils.getSystemColor(context, R.color.sky_color_f2f2f2))); allCommentAdaptor = new AllCommentAdaptor(context, commentResponses); mLuRecyclerViewAdapter = new LuRecyclerViewAdapter(allCommentAdaptor); mRecyclerView.setAdapter(mLuRecyclerViewAdapter); mRecyclerView.setOnLoadMoreListener(new OnLoadMoreListener() { @Override public void onLoadMore() { if (iAllCommentPresenter.hasMore()){ loadData(); } else { mRecyclerView.setNoMore(true); } } }); //设置底部加载颜色 mRecyclerView.setFooterViewColor(R.color.main_colorAccent, R.color.main_colorAccent ,android.R.color.white); //设置底部加载文字提示 mRecyclerView.setFooterViewHint("拼命加载中", "已经全部加载完", "网络不给力啊,点击再试一次吧"); onRefresh(); //请求个人主页信息 ProductIntroduceIn productIntroduceIn = new ProductIntroduceIn(); productIntroduceIn.setUser_id(seller_id); getPresenter().requestCardInfo(productIntroduceIn); //查询评论数量 searchCommentNum(); } @Override protected void init() { title.setText(R.string.app_card_string); toolbar.setNavigationIcon(R.mipmap.app_back_arrow_icon); toolbar.inflateMenu(R.menu.app_share_menu); //设置刷新时动画的颜色,可以设置4个 if (mSwipeRefreshLayout != null) { mSwipeRefreshLayout.setProgressViewOffset(false, 0, AppUtils.dip2px(context, 48)); mSwipeRefreshLayout.setColorSchemeResources(R.color.main_colorPrimary); mSwipeRefreshLayout.setOnRefreshListener(this); } seller_id = getIntent().getStringExtra("seller_id"); commentRequest.setType(1);//商户编号 commentRequest.setValue(seller_id); radioGroup.check(R.id.all); } @Override public void showError(String error) { super.showError(error); T.showShort(context, error); mSwipeRefreshLayout.setRefreshing(false); } @Override protected void onDestoryActivity() { } @Override public void showCollectView(String msg) { T.showShort(context, msg); switch (tag){ case 1: collectBtn.setText("收藏"); break; case 2: collectBtn.setText("已收藏"); break; case 3: collect.setText("收藏"); AppUtils.changeTextViewIcon(context, collect, R.mipmap.app_product_detail_star_icon, 2); break; case 4: collect.setText("已收藏"); AppUtils.changeTextViewIcon(context, collect, R.mipmap.app_product_detail_selected_star_icon, 2); break; } } @Override public void showCollectError(String error) { T.showShort(context, error); switch (tag){ case 1: collectBtn.setText("已收藏"); break; case 2: collectBtn.setText("收藏"); break; case 3: collect.setText("已收藏"); AppUtils.changeTextViewIcon(context, collect, R.mipmap.app_product_detail_selected_star_icon, 2); break; case 4: collect.setText("收藏"); AppUtils.changeTextViewIcon(context, collect, R.mipmap.app_product_detail_star_icon, 2); break; } } @Override public void getRefreshData(List<CommentResponse> list, int tag, int num) { switch (tag){ case 1: allBtn.setText("全部(" + num + ")"); break; case 2: picBtn.setText("有图(" + num + ")"); break; } allCommentAdaptor.add(list); if(mSwipeRefreshLayout.isRefreshing()){ mSwipeRefreshLayout.setRefreshing(false); } mRecyclerView.refreshComplete(20); mLuRecyclerViewAdapter.notifyDataSetChanged(); } @Override public void getLoadMoreData(List<CommentResponse> list, int tag, int num) { switch (tag){ case 1: allBtn.setText("全部(" + num + ")"); break; case 2: picBtn.setText("有图(" + num + ")"); break; } allCommentAdaptor.addAll(list); mSwipeRefreshLayout.setRefreshing(false); mRecyclerView.refreshComplete(20); mLuRecyclerViewAdapter.notifyDataSetChanged(); } @Override public void onRefresh() { mSwipeRefreshLayout.setRefreshing(true); mRecyclerView.setRefreshing(true); refresh(); } @OnClick({R.id.all, R.id.has_pic}) void clickSelectPic(RadioButton radioButton){ switch (radioButton.getId()){ case R.id.all: commentRequest.setPic_type(""); onRefresh(); break; case R.id.has_pic: commentRequest.setPic_type("1"); onRefresh(); break; } } @OnClick({R.id.navigate}) void turnToMap(){ Intent intent=new Intent(this, BaiduMapActivity.class); startActivity(intent); } @OnClick(R.id.app_call_phone) void call(){ if (null == productIntroduceOut || TextUtils.isEmpty(productIntroduceOut.getMobile())){ T.showShort(context, "找不到号码"); return; } AppUtils.callPhone(context, productIntroduceOut.getMobile()); } private int tag = -1; @OnClick(R.id.app_collect) void clickCollect(){ CollectPubIn collectPubIn = new CollectPubIn(); collectPubIn.setType("2"); collectPubIn.setCollect_value(seller_id); if ("已收藏".equals(collect.getText().toString())){ iCollectionPresenter.cancelCollect(collectPubIn); tag = 3; } else { tag = 4; iCollectionPresenter.requestCollect(collectPubIn); } } @OnClick(R.id.shop_collect) void collect(){ CollectPubIn collectPubIn = new CollectPubIn(); collectPubIn.setType("2"); collectPubIn.setCollect_value(seller_id); if ("已收藏".equals(collectBtn.getText().toString())){ tag = 1; iCollectionPresenter.cancelCollect(collectPubIn); } else { tag = 2; iCollectionPresenter.requestCollect(collectPubIn); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); ShareUtils.onActivityResult(this, requestCode, resultCode, data); } @Override public void responseCardInfo(ProductIntroduceOut productIntroduceOut) { this.productIntroduceOut = productIntroduceOut; ImageHelper.getInstance().displayDefinedImage(productIntroduceOut.getPic_url(), appIcon, R.mipmap.app_default_icon, R.mipmap.app_default_icon); userName.setText(productIntroduceOut.getNick_name()); appTime.setText("从业时间:" + (TextUtils.isEmpty(productIntroduceOut.getWorktime()) ? "" : productIntroduceOut.getWorktime())); mainSell.setText("主营业务:" + (TextUtils.isEmpty(productIntroduceOut.getMain_business_desc()) ? "" : productIntroduceOut.getMain_business_desc())); if (1 == productIntroduceOut.getIs_collect()){ collect.setText("已收藏"); AppUtils.changeTextViewIcon(context, collect, R.mipmap.app_product_detail_selected_star_icon, 2); collectBtn.setText("已收藏"); }else{ collect.setText("收藏"); collectBtn.setText("收藏"); AppUtils.changeTextViewIcon(context, collect, R.mipmap.app_product_detail_star_icon, 2); } // qq.setText(productIntroduceOut.getQq()); // weixin.setText(productIntroduceOut.getWeixin()); } /** * 刷新数据 */ private void refresh(){ if (TextUtils.isEmpty(commentRequest.getPic_type())){ iAllCommentPresenter.loadData(commentRequest, 1); }else{ iAllCommentPresenter.loadData(commentRequest, 2); } } /** * 加载数据 */ private void loadData(){ if (TextUtils.isEmpty(commentRequest.getPic_type())) { iAllCommentPresenter.loadMore(commentRequest, 1); }else{ iAllCommentPresenter.loadMore(commentRequest, 2); } } /** * 搜索评论数量 */ private void searchCommentNum() { iAllCommentPresenter.requestAllCommentNum(commentRequest); } @Override public void responseAllCommentNum(int all) { allBtn.setText("全部(" + all + ")"); } @Override public void responsePicNum(int pic) { picBtn.setText("有图(" + pic + ")"); } @Override public void showProgress() { super.showProgress(); DialogUtils.showLoading(this); } @Override public void hideProgress() { super.hideProgress(); DialogUtils.hideLoading(); } @OnClick(R.id.publish_comment) void skipComment(){ Intent r = new Intent(context, CommentActivity.class); r.putExtra("image", productIntroduceOut.getPic_url()); r.putExtra("type", 1);//0 订单 1 商户 r.putExtra("about_user_id", seller_id); startActivity(r); } }
14,588
0.633782
0.630136
435
31.786207
25.146244
132
false
false
0
0
0
0
0
0
0.634483
false
false
13
fa4e67e0880d4ff594c373842dd6af9eb516286d
25,159,918,433,752
806b9c276e61c756bd8807136715ad46acf97dca
/core java/Core Java/src/org/core/java/StringTest.java
953a10543fecb209853d7b0dd0500c5846471888
[]
no_license
sekhar507/JavaPjct
https://github.com/sekhar507/JavaPjct
ed8e8404fba1eebf6960cbfd1985a5ba9649f02a
326c043a8257d12f277d8b32c043526a840b2523
refs/heads/master
2021-01-22T22:39:52.787000
2017-05-29T23:28:49
2017-05-29T23:28:49
92,782,541
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.core.java; public class StringTest { public String getName() { String name ="Sai kumar"; return name.substring(4); } }
UTF-8
Java
152
java
StringTest.java
Java
[ { "context": "st {\n\tpublic String getName() \n\t{\n\t\tString name =\"Sai kumar\";\n\t\treturn name.substring(4);\n\t\t\n\t}\n\n}\n", "end": 112, "score": 0.9998481869697571, "start": 103, "tag": "NAME", "value": "Sai kumar" } ]
null
[]
package org.core.java; public class StringTest { public String getName() { String name ="<NAME>"; return name.substring(4); } }
149
0.631579
0.625
19
7
10.940028
27
false
false
0
0
0
0
0
0
0.631579
false
false
13
91cd3c1d25729b0e32a9f8f3f3a9e6e135106ad1
33,285,996,551,535
05de6a096dbf47fddd4d4573c3ef540d0c84a120
/app/src/main/java/com/example/asvladimirov/randomuser/Adapter/UserViewHolder.java
369bade8615d216c91e64fdc1ba1a5a9aa675f2a
[]
no_license
AleksandrVladimirov/RandomUser
https://github.com/AleksandrVladimirov/RandomUser
337cb6c98db7b1afb6638b22659e130726f50c9b
61a6b3a67eb5f8633a0840d7388e5faffeaf3494
refs/heads/master
2020-04-11T11:53:14.656000
2018-12-14T09:32:06
2018-12-14T09:32:06
161,760,474
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.asvladimirov.randomuser.Adapter; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.example.asvladimirov.randomuser.Model.User; import com.example.asvladimirov.randomuser.MyInterface.OnUserSelectedListener; import com.example.asvladimirov.randomuser.R; import com.squareup.picasso.Picasso; public class UserViewHolder extends RecyclerView.ViewHolder{ public ImageView imageUser; public TextView titleNameUser; public TextView firstNameUser; public TextView lastNameUser; public UserViewHolder(@NonNull View itemView) { super(itemView); imageUser = itemView.findViewById(R.id.imageUser); titleNameUser = itemView.findViewById(R.id.titleNameUser); firstNameUser = itemView.findViewById(R.id.firstNameUser); lastNameUser = itemView.findViewById(R.id.lastNameUser); } void bind(User users, final OnUserSelectedListener listener, int i){ String title = users.getName().getTitle(); String firstName = users.getName().getFirstName(); String lastName = users.getName().getLastName(); if(users != null){ Picasso.get() .load(users.getPicture().getMedium()) .transform(new CircularTransformation()) .resize(100, 100) .into(imageUser); title = title.substring(0,1).toUpperCase() + title.substring(1).toLowerCase(); firstName = firstName.substring(0,1).toUpperCase() + firstName.substring(1).toLowerCase(); lastName = lastName.substring(0,1).toUpperCase() + lastName.substring(1).toLowerCase(); titleNameUser.setText(title); firstNameUser.setText(firstName); lastNameUser.setText(lastName); } else { firstNameUser.setText("Loading..."); } final String firstNameFinal = firstName; final String lastNameFinal = lastName; final String picture = users != null ? users.getPicture().getLarge() : null; final String gender = users != null ? users.getGender() : null; final String DOB = users != null ? users.getDob().getDate() : null; final String age = users != null ? users.getDob().getAge() : null; final String phone = users != null ? users.getPhone() : null; final String cell = users != null ? users.getCell() : null; final String email = users != null ? users.getEmail() : null; final String postcode = users != null ? users.getLocation().getPostcode() : null; final String state = users != null ? users.getLocation().getState() : null; final String city = users != null ? users.getLocation().getCity() : null; final String street = users != null ? users.getLocation().getStreet() : null; itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(listener != null){ listener.onUserSelectedListened(picture, firstNameFinal, lastNameFinal, gender, DOB, age, phone, cell, email, postcode, state, city, street); } } }); } }
UTF-8
Java
3,325
java
UserViewHolder.java
Java
[ { "context": "package com.example.asvladimirov.randomuser.Adapter;\n\nimport android.support.a", "end": 28, "score": 0.5952590703964233, "start": 20, "tag": "USERNAME", "value": "asvladim" }, { "context": "package com.example.asvladimirov.randomuser.Adapter;\n\nimport android.support...
null
[]
package com.example.asvladimirov.randomuser.Adapter; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.example.asvladimirov.randomuser.Model.User; import com.example.asvladimirov.randomuser.MyInterface.OnUserSelectedListener; import com.example.asvladimirov.randomuser.R; import com.squareup.picasso.Picasso; public class UserViewHolder extends RecyclerView.ViewHolder{ public ImageView imageUser; public TextView titleNameUser; public TextView firstNameUser; public TextView lastNameUser; public UserViewHolder(@NonNull View itemView) { super(itemView); imageUser = itemView.findViewById(R.id.imageUser); titleNameUser = itemView.findViewById(R.id.titleNameUser); firstNameUser = itemView.findViewById(R.id.firstNameUser); lastNameUser = itemView.findViewById(R.id.lastNameUser); } void bind(User users, final OnUserSelectedListener listener, int i){ String title = users.getName().getTitle(); String firstName = users.getName().getFirstName(); String lastName = users.getName().getLastName(); if(users != null){ Picasso.get() .load(users.getPicture().getMedium()) .transform(new CircularTransformation()) .resize(100, 100) .into(imageUser); title = title.substring(0,1).toUpperCase() + title.substring(1).toLowerCase(); firstName = firstName.substring(0,1).toUpperCase() + firstName.substring(1).toLowerCase(); lastName = lastName.substring(0,1).toUpperCase() + lastName.substring(1).toLowerCase(); titleNameUser.setText(title); firstNameUser.setText(firstName); lastNameUser.setText(lastName); } else { firstNameUser.setText("Loading..."); } final String firstNameFinal = firstName; final String lastNameFinal = lastName; final String picture = users != null ? users.getPicture().getLarge() : null; final String gender = users != null ? users.getGender() : null; final String DOB = users != null ? users.getDob().getDate() : null; final String age = users != null ? users.getDob().getAge() : null; final String phone = users != null ? users.getPhone() : null; final String cell = users != null ? users.getCell() : null; final String email = users != null ? users.getEmail() : null; final String postcode = users != null ? users.getLocation().getPostcode() : null; final String state = users != null ? users.getLocation().getState() : null; final String city = users != null ? users.getLocation().getCity() : null; final String street = users != null ? users.getLocation().getStreet() : null; itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(listener != null){ listener.onUserSelectedListened(picture, firstNameFinal, lastNameFinal, gender, DOB, age, phone, cell, email, postcode, state, city, street); } } }); } }
3,325
0.649925
0.645113
75
43.333332
31.396107
161
false
false
0
0
0
0
0
0
0.84
false
false
13
4c87fe9f272a9f91e167a937122f5a67944328ac
15,272,903,724,851
e376d9c9012527f150c7c48b800eb58c9ca4c1a8
/src/main/java/controller/Profile.java
e05a66bde47107214ec61e1f87eab854bc7d42a1
[]
no_license
Zenas22/login
https://github.com/Zenas22/login
ee67dc9ef706928dee98a6e0ab88438ffb6055d8
1b18a70094dd041e3c6c54d57b4b9396efe2660d
refs/heads/master
2020-05-31T02:41:02.562000
2017-05-07T13:36:37
2017-05-07T13:36:37
190,070,744
0
1
null
true
2019-06-03T19:40:21
2019-06-03T19:40:21
2017-05-07T05:51:33
2017-05-07T13:36:38
10
0
0
0
null
false
false
package controller; import Utils.SQLUtils; import dao.User; import org.json.JSONObject; import spark.Request; import spark.Response; import java.util.Optional; public class Profile { Request _request; Response _response; private final static int MAX_SESSION_DURATION_SECS = 3600; public Profile(Request request, Response response) { _request = request; _response = response; } public String get() { String userName = _request.params(":username"); JSONObject response = new JSONObject(); if (!userName.isEmpty()) { SQLUtils conn = new SQLUtils(); Optional<User> oUser = User.getPublicUserInfo(conn, userName); if (oUser.isPresent()) { User user = oUser.get(); response.put("username", user._user_name); response.put("info", user._info); } else { _response.status(404); } } else { _response.status(400); } return response.toString(); } public String update() { JSONObject response = new JSONObject(); String session = ""; String userName = ""; String newUserName = ""; String newInfo = ""; try { JSONObject body = new JSONObject(_request.body()); userName = body.getString("username"); session = body.getString("session"); if (body.has("new_username")) { newUserName = body.getString("new_username"); } if (body.has("new_info")) { newInfo = body.getString("new_info"); } } catch (Exception e) { response.put("error_message", "Could not update profile"); _response.status(400); return response.toString(); } SQLUtils conn = new SQLUtils(); if (User.validateSession(conn, session, userName, MAX_SESSION_DURATION_SECS)) { if (User.updateProfile(conn, userName, newUserName, newInfo)) { return response.toString(); } else { response.put("error_message", "Could not update profile"); return response.toString(); } } else { _response.status(401); return response.toString(); } } public String changePassword() { JSONObject response = new JSONObject(); String userName = ""; String password = ""; String newPassword = ""; String newPasswordConfirm = ""; String session = ""; boolean useSession = false; try { JSONObject body = new JSONObject(_request.body()); userName = body.getString("username"); newPassword = body.getString("new_password"); newPasswordConfirm = body.getString("new_password_confirm"); if (!newPassword.equals(newPasswordConfirm)) { response.put("error_message", "New Passwords don't match"); _response.status(400); return response.toString(); } if (body.has("session")) { session = body.getString("session"); useSession = true; } if (session.isEmpty()) { password = body.getString("password"); useSession = false; } } catch (Exception e) { response.put("error_message", "Could not change password"); _response.status(401); return response.toString(); } SQLUtils conn = new SQLUtils(); boolean changePassword = false; if (useSession) { if (User.validateSession(conn, session, userName, MAX_SESSION_DURATION_SECS)) { changePassword = true; } else { response.put("error_message", "Session expired. Please login."); _response.status(401); return response.toString(); } } else { if (User.validateLogin(conn, userName, password)) { changePassword = true; } else { _response.status(401); return response.toString(); } } if (changePassword) { if (User.changePassword(conn, userName, newPassword)) { return response.toString(); } else { response.put("error_message", "Could not update password"); _response.status(500); return response.toString(); } } else { _response.status(500); return response.toString(); } } public String delete() { JSONObject response = new JSONObject(); String userName = ""; String password = ""; String session = ""; try { JSONObject body = new JSONObject(_request.body()); userName = body.getString("username"); password = body.getString("password"); session = body.getString("session"); } catch (Exception e) { response.put("error_message", "Invalid delete request"); return response.toString(); } System.out.println("Received Delete Request for user: " + userName); SQLUtils conn = new SQLUtils(); boolean deleted = false; if (User.validateLogin(conn, userName, password) && User.validateSession(conn, session, userName, MAX_SESSION_DURATION_SECS)) { deleted = User.deleteUser(conn, userName); } if (!deleted) { _response.status(400); response.put("error_message", "Could not delete user"); } return response.toString(); } }
UTF-8
Java
5,874
java
Profile.java
Java
[ { "context": "t.body());\n userName = body.getString(\"username\");\n session = body.getString(\"session\"", "end": 1399, "score": 0.9958022236824036, "start": 1391, "tag": "USERNAME", "value": "username" }, { "context": "t.body());\n userName = body....
null
[]
package controller; import Utils.SQLUtils; import dao.User; import org.json.JSONObject; import spark.Request; import spark.Response; import java.util.Optional; public class Profile { Request _request; Response _response; private final static int MAX_SESSION_DURATION_SECS = 3600; public Profile(Request request, Response response) { _request = request; _response = response; } public String get() { String userName = _request.params(":username"); JSONObject response = new JSONObject(); if (!userName.isEmpty()) { SQLUtils conn = new SQLUtils(); Optional<User> oUser = User.getPublicUserInfo(conn, userName); if (oUser.isPresent()) { User user = oUser.get(); response.put("username", user._user_name); response.put("info", user._info); } else { _response.status(404); } } else { _response.status(400); } return response.toString(); } public String update() { JSONObject response = new JSONObject(); String session = ""; String userName = ""; String newUserName = ""; String newInfo = ""; try { JSONObject body = new JSONObject(_request.body()); userName = body.getString("username"); session = body.getString("session"); if (body.has("new_username")) { newUserName = body.getString("new_username"); } if (body.has("new_info")) { newInfo = body.getString("new_info"); } } catch (Exception e) { response.put("error_message", "Could not update profile"); _response.status(400); return response.toString(); } SQLUtils conn = new SQLUtils(); if (User.validateSession(conn, session, userName, MAX_SESSION_DURATION_SECS)) { if (User.updateProfile(conn, userName, newUserName, newInfo)) { return response.toString(); } else { response.put("error_message", "Could not update profile"); return response.toString(); } } else { _response.status(401); return response.toString(); } } public String changePassword() { JSONObject response = new JSONObject(); String userName = ""; String password = ""; String newPassword = ""; String newPasswordConfirm = ""; String session = ""; boolean useSession = false; try { JSONObject body = new JSONObject(_request.body()); userName = body.getString("username"); newPassword = body.getString("new_password"); newPasswordConfirm = body.getString("new_password_confirm"); if (!newPassword.equals(newPasswordConfirm)) { response.put("error_message", "New Passwords don't match"); _response.status(400); return response.toString(); } if (body.has("session")) { session = body.getString("session"); useSession = true; } if (session.isEmpty()) { password = body.getString("password"); useSession = false; } } catch (Exception e) { response.put("error_message", "Could not change password"); _response.status(401); return response.toString(); } SQLUtils conn = new SQLUtils(); boolean changePassword = false; if (useSession) { if (User.validateSession(conn, session, userName, MAX_SESSION_DURATION_SECS)) { changePassword = true; } else { response.put("error_message", "Session expired. Please login."); _response.status(401); return response.toString(); } } else { if (User.validateLogin(conn, userName, password)) { changePassword = true; } else { _response.status(401); return response.toString(); } } if (changePassword) { if (User.changePassword(conn, userName, newPassword)) { return response.toString(); } else { response.put("error_message", "Could not update password"); _response.status(500); return response.toString(); } } else { _response.status(500); return response.toString(); } } public String delete() { JSONObject response = new JSONObject(); String userName = ""; String password = ""; String session = ""; try { JSONObject body = new JSONObject(_request.body()); userName = body.getString("username"); password = body.<PASSWORD>("<PASSWORD>"); session = body.getString("session"); } catch (Exception e) { response.put("error_message", "Invalid delete request"); return response.toString(); } System.out.println("Received Delete Request for user: " + userName); SQLUtils conn = new SQLUtils(); boolean deleted = false; if (User.validateLogin(conn, userName, password) && User.validateSession(conn, session, userName, MAX_SESSION_DURATION_SECS)) { deleted = User.deleteUser(conn, userName); } if (!deleted) { _response.status(400); response.put("error_message", "Could not delete user"); } return response.toString(); } }
5,877
0.527409
0.52111
201
28.223881
23.093679
91
false
false
0
0
0
0
0
0
0.621891
false
false
13
3712efdb11efad9897e7039dc3c771f62653ed0b
17,162,689,334,815
62be71a3622603feff4e0c7039670bcf63e25123
/src/com/liuruichao/knn/Point.java
fa00476a09395077c1cd2bf775d32f2d04df4d0b
[]
no_license
liuruichao555/data_struct
https://github.com/liuruichao555/data_struct
e4f430342d2a8003b087d2242c07c19a08ff31b9
148c8f18554f601144dacdb8e4641c4706538026
refs/heads/master
2017-11-08T09:56:13.984000
2017-09-21T05:32:54
2017-09-21T05:32:54
83,631,179
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.liuruichao.knn; /** * Point * * @author liuruichao * Created on 2017/9/20 15:28 */ public class Point { private int ID; private double x; private double y; private String type; public Point(int ID, double x, double y) { this.ID = ID; this.x = x; this.y = y; } public Point(int ID, double x, double y, String type) { this.ID = ID; this.x = x; this.y = y; this.type = type; } public int getID() { return ID; } public void setID(int ID) { this.ID = ID; } public double getX() { return x; } public void setX(double x) { this.x = x; } public double getY() { return y; } public void setY(double y) { this.y = y; } public String getType() { return type; } public void setType(String type) { this.type = type; } }
UTF-8
Java
953
java
Point.java
Java
[ { "context": "ge com.liuruichao.knn;\n\n/**\n * Point\n *\n * @author liuruichao\n * Created on 2017/9/20 15:28\n */\npublic class Po", "end": 66, "score": 0.9989633560180664, "start": 56, "tag": "USERNAME", "value": "liuruichao" } ]
null
[]
package com.liuruichao.knn; /** * Point * * @author liuruichao * Created on 2017/9/20 15:28 */ public class Point { private int ID; private double x; private double y; private String type; public Point(int ID, double x, double y) { this.ID = ID; this.x = x; this.y = y; } public Point(int ID, double x, double y, String type) { this.ID = ID; this.x = x; this.y = y; this.type = type; } public int getID() { return ID; } public void setID(int ID) { this.ID = ID; } public double getX() { return x; } public void setX(double x) { this.x = x; } public double getY() { return y; } public void setY(double y) { this.y = y; } public String getType() { return type; } public void setType(String type) { this.type = type; } }
953
0.500525
0.488982
62
14.370968
13.089314
59
false
false
0
0
0
0
0
0
0.403226
false
false
13
f14d18aab670223b9333807d1bc777d6d41bff77
1,288,490,217,024
8ccff1a5b5370f62e33f3f9cfde18de062dfe08d
/.svn/pristine/21/218e81b38a5980a311f7779014eb2416ef1694dc.svn-base
05bec291d33998126e97301bee666172d26f16b4
[]
no_license
yinhanxy/volunteer
https://github.com/yinhanxy/volunteer
1b00f58279302e36b6aa58dd2b539dc830e07996
a4ff20549df4a29451fe8d83242a9a05b3bb008b
refs/heads/master
2021-04-26T23:57:54.416000
2018-03-05T09:32:30
2018-03-05T09:32:30
123,886,846
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.topstar.volunteer.mapper; import java.util.List; import java.util.Map; import org.apache.ibatis.annotations.Param; import com.topstar.volunteer.entity.Volunteer; import com.topstar.volunteer.model.Statistics; import com.topstar.volunteer.model.VolunteerView; import com.topstar.volunteer.util.BaseMapper; public interface VolunteerMapper extends BaseMapper<Volunteer>{ /** * 通过志愿者实体字段过滤查询志愿者名单信息列表 * @param volunteer * @return */ List<VolunteerView> findByEntity(@Param("volunteer")Volunteer volunteer); /** * 通过志愿者实体字段过滤查询志愿者考核信息列表 * @param volunteer * @return */ List<VolunteerView> findVolunteerCheckByEntity(@Param("volunteer")Volunteer volunteer); /** * 批量重置志愿者初始密码 * @param params * @return */ public int setVolunteerPassword(Map<String,Object> params); /** * 通过idCard查询得到志愿者Id * @param idCard * @return */ public Long selectVolId(@Param("idcard")String idcard); /** * 根据志愿者Id修改退队管理状态 * @param volId * @param retreatTeamStatus * @return */ public int editRetreatTeamStatus(@Param("volId")Long volId,@Param("retreatTeamStatus")Long retreatTeamStatus); /** * 志愿者统计页面信息 * @return */ public List<Statistics> statisticsShow(@Param("statistics")Statistics statistics); /** * 根据机构trainId得到该机构下的用户列表 * @param trainId * @param volunteer * @return */ public List<Volunteer> getVolByOrgId(@Param("trainId")Long trainId,@Param("volunteer")Volunteer volunteer); /** * 根据机构orgId得到该机构下的用户列表 * @param orgId * @return */ List<Volunteer> getVols(@Param("orgId")Long orgId); /** * 得到志愿者比例信息(如,男女比例,政治面貌,学历信息) * @param statistics * @return */ public Statistics getVolInfo(@Param("statistics")Statistics statistics); /** * 得到志愿者比例信息按照服务队划分 * @param statistics * @return */ List<Statistics> getVolInfoList(@Param("statistics")Statistics statistics); /** * 得到志愿者统计信息(名称,注册时间,服务时长,活动次数) * @param statistics * @return */ List<Statistics> getVolStatis(@Param("statistics")Statistics statistics); }
UTF-8
Java
2,381
218e81b38a5980a311f7779014eb2416ef1694dc.svn-base
Java
[]
null
[]
package com.topstar.volunteer.mapper; import java.util.List; import java.util.Map; import org.apache.ibatis.annotations.Param; import com.topstar.volunteer.entity.Volunteer; import com.topstar.volunteer.model.Statistics; import com.topstar.volunteer.model.VolunteerView; import com.topstar.volunteer.util.BaseMapper; public interface VolunteerMapper extends BaseMapper<Volunteer>{ /** * 通过志愿者实体字段过滤查询志愿者名单信息列表 * @param volunteer * @return */ List<VolunteerView> findByEntity(@Param("volunteer")Volunteer volunteer); /** * 通过志愿者实体字段过滤查询志愿者考核信息列表 * @param volunteer * @return */ List<VolunteerView> findVolunteerCheckByEntity(@Param("volunteer")Volunteer volunteer); /** * 批量重置志愿者初始密码 * @param params * @return */ public int setVolunteerPassword(Map<String,Object> params); /** * 通过idCard查询得到志愿者Id * @param idCard * @return */ public Long selectVolId(@Param("idcard")String idcard); /** * 根据志愿者Id修改退队管理状态 * @param volId * @param retreatTeamStatus * @return */ public int editRetreatTeamStatus(@Param("volId")Long volId,@Param("retreatTeamStatus")Long retreatTeamStatus); /** * 志愿者统计页面信息 * @return */ public List<Statistics> statisticsShow(@Param("statistics")Statistics statistics); /** * 根据机构trainId得到该机构下的用户列表 * @param trainId * @param volunteer * @return */ public List<Volunteer> getVolByOrgId(@Param("trainId")Long trainId,@Param("volunteer")Volunteer volunteer); /** * 根据机构orgId得到该机构下的用户列表 * @param orgId * @return */ List<Volunteer> getVols(@Param("orgId")Long orgId); /** * 得到志愿者比例信息(如,男女比例,政治面貌,学历信息) * @param statistics * @return */ public Statistics getVolInfo(@Param("statistics")Statistics statistics); /** * 得到志愿者比例信息按照服务队划分 * @param statistics * @return */ List<Statistics> getVolInfoList(@Param("statistics")Statistics statistics); /** * 得到志愿者统计信息(名称,注册时间,服务时长,活动次数) * @param statistics * @return */ List<Statistics> getVolStatis(@Param("statistics")Statistics statistics); }
2,381
0.71633
0.71633
92
21.043478
25.291739
111
false
false
0
0
0
0
0
0
1.141304
false
false
13
76cb2e687242a2d1fc74b3cb9b1fd2d3c572a5ce
7,782,480,761,482
aae97637aa401a69995348c0c2f964ce1de22bae
/Final_submission/Application/Android/app/src/main/java/com/paytel/transaction/apicall_transaction.java
12cfc7d98de7bdeebaacc31558d9307a0ffccb53
[]
no_license
Calandra-a/PAyTEL
https://github.com/Calandra-a/PAyTEL
b5169e1bcc698bb3bf4bcfe62c8befad1455d7fa
de92bbd74a5348d14f7e905b5afacfbacac22dfa
refs/heads/master
2020-03-28T08:20:36.786000
2018-12-11T04:55:59
2018-12-11T04:55:59
147,958,801
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.paytel.transaction; import android.app.Activity; import android.util.Log; import com.amazonaws.http.HttpMethodName; import com.amazonaws.mobile.auth.core.IdentityManager; import com.amazonaws.mobile.client.AWSMobileClient; import com.amazonaws.mobileconnectors.apigateway.ApiClientFactory; import com.amazonaws.mobileconnectors.apigateway.ApiRequest; import com.amazonaws.mobileconnectors.apigateway.ApiResponse; import com.amazonaws.util.IOUtils; import com.paytel.util.api.idyonkpcbig0.UsertransactionMobileHubClient; import org.json.JSONException; import org.json.JSONObject; import java.io.InputStream; import java.util.HashMap; import java.util.Map; public class apicall_transaction { private static final String LOG_TAG = apicall_transaction.class.getSimpleName(); ApiResponse responseVal = null; Object[] responseArray = new Object[2]; String responseData; private UsertransactionMobileHubClient apiClient; public Object[] callCloudLogic(String transID, String requesttype, String biometric) { apiClient =new ApiClientFactory() .credentialsProvider(AWSMobileClient.getInstance().getCredentialsProvider()) .build(UsertransactionMobileHubClient.class); String userID =IdentityManager.getDefaultIdentityManager().getCachedUserID(); // Create components of api request final String method = "POST"; final String path = "/complete-transaction"; JSONObject json = new JSONObject(); try { json.put("user_id", userID); json.put("transaction_id", transID); json.put("request", requesttype); json.put("biometric", biometric); } catch (JSONException e) { e.printStackTrace(); } final String body = json.toString(); System.out.println(body); final Map parameters = new HashMap<>(); parameters.put("lang", "en_US"); final Map headers = new HashMap<>(); // Use components to create the api request ApiRequest localRequest = new ApiRequest(apiClient.getClass().getSimpleName()) .withPath(path) .withHttpMethod(HttpMethodName.valueOf(method)) .withHeaders(headers) .addHeader("Content-Type", "application/json") .withParameters(parameters); // Only set body if it has content. //if (body.length() > 0) { System.out.println(body.length()); localRequest = localRequest .addHeader("Content-Length", String.valueOf(body.length())) .withBody(body); // } final ApiRequest request = localRequest; // Make network call on background thread //new Thread(new Runnable() { // @Override // public void run() { try { Log.d(LOG_TAG, "Invoking API w/ Request : " + request.getHttpMethod() + ":" + request.getPath()); ApiResponse response = apiClient.execute(request); final InputStream responseContentStream = response.getContent(); if (responseContentStream != null) { responseData = IOUtils.toString(responseContentStream); Log.d(LOG_TAG, "Response : " + responseData); } responseVal = response; responseArray[0] = responseVal; responseArray[1] = responseData; Log.d(LOG_TAG, response.getStatusCode() + " " + response.getStatusText()); } catch (final Exception exception) { Log.e(LOG_TAG, exception.getMessage(), exception); exception.printStackTrace(); } return responseArray; } //}).start(); }
UTF-8
Java
3,891
java
apicall_transaction.java
Java
[]
null
[]
package com.paytel.transaction; import android.app.Activity; import android.util.Log; import com.amazonaws.http.HttpMethodName; import com.amazonaws.mobile.auth.core.IdentityManager; import com.amazonaws.mobile.client.AWSMobileClient; import com.amazonaws.mobileconnectors.apigateway.ApiClientFactory; import com.amazonaws.mobileconnectors.apigateway.ApiRequest; import com.amazonaws.mobileconnectors.apigateway.ApiResponse; import com.amazonaws.util.IOUtils; import com.paytel.util.api.idyonkpcbig0.UsertransactionMobileHubClient; import org.json.JSONException; import org.json.JSONObject; import java.io.InputStream; import java.util.HashMap; import java.util.Map; public class apicall_transaction { private static final String LOG_TAG = apicall_transaction.class.getSimpleName(); ApiResponse responseVal = null; Object[] responseArray = new Object[2]; String responseData; private UsertransactionMobileHubClient apiClient; public Object[] callCloudLogic(String transID, String requesttype, String biometric) { apiClient =new ApiClientFactory() .credentialsProvider(AWSMobileClient.getInstance().getCredentialsProvider()) .build(UsertransactionMobileHubClient.class); String userID =IdentityManager.getDefaultIdentityManager().getCachedUserID(); // Create components of api request final String method = "POST"; final String path = "/complete-transaction"; JSONObject json = new JSONObject(); try { json.put("user_id", userID); json.put("transaction_id", transID); json.put("request", requesttype); json.put("biometric", biometric); } catch (JSONException e) { e.printStackTrace(); } final String body = json.toString(); System.out.println(body); final Map parameters = new HashMap<>(); parameters.put("lang", "en_US"); final Map headers = new HashMap<>(); // Use components to create the api request ApiRequest localRequest = new ApiRequest(apiClient.getClass().getSimpleName()) .withPath(path) .withHttpMethod(HttpMethodName.valueOf(method)) .withHeaders(headers) .addHeader("Content-Type", "application/json") .withParameters(parameters); // Only set body if it has content. //if (body.length() > 0) { System.out.println(body.length()); localRequest = localRequest .addHeader("Content-Length", String.valueOf(body.length())) .withBody(body); // } final ApiRequest request = localRequest; // Make network call on background thread //new Thread(new Runnable() { // @Override // public void run() { try { Log.d(LOG_TAG, "Invoking API w/ Request : " + request.getHttpMethod() + ":" + request.getPath()); ApiResponse response = apiClient.execute(request); final InputStream responseContentStream = response.getContent(); if (responseContentStream != null) { responseData = IOUtils.toString(responseContentStream); Log.d(LOG_TAG, "Response : " + responseData); } responseVal = response; responseArray[0] = responseVal; responseArray[1] = responseData; Log.d(LOG_TAG, response.getStatusCode() + " " + response.getStatusText()); } catch (final Exception exception) { Log.e(LOG_TAG, exception.getMessage(), exception); exception.printStackTrace(); } return responseArray; } //}).start(); }
3,891
0.619121
0.617836
118
31.974577
25.509209
92
false
false
0
0
0
0
0
0
0.567797
false
false
13
ad45fe47eda9c80b3a4c6193ebb2ace17e2dd275
19,937,238,214,748
a04c01531a96af4486479afa02789206f572a496
/src/day14_multi_branch_if_statements/IfWithoutElse.java
3a29d5839afe20d98777f4d4936c867e85e80848
[]
no_license
semihagnyldz/java-programming-course
https://github.com/semihagnyldz/java-programming-course
07be5d9cad0a472bbe11cc2349cae4370041ed23
44456db0533d412e0b69c84c738c2e8050b3bce5
refs/heads/master
2023-06-02T06:35:55.687000
2021-06-19T18:22:29
2021-06-19T18:22:29
371,730,892
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package day14_multi_branch_if_statements; import java.util.Scanner; public class IfWithoutElse { public static void main(String[] args) { System.out.println("Enter the year: "); Scanner input=new Scanner(System.in); double year= input.nextDouble(); //boolean enter= year==2020; if(year==2020){ System.out.println("cover up mask"); } } }
UTF-8
Java
406
java
IfWithoutElse.java
Java
[]
null
[]
package day14_multi_branch_if_statements; import java.util.Scanner; public class IfWithoutElse { public static void main(String[] args) { System.out.println("Enter the year: "); Scanner input=new Scanner(System.in); double year= input.nextDouble(); //boolean enter= year==2020; if(year==2020){ System.out.println("cover up mask"); } } }
406
0.615764
0.591133
14
28
17.154758
48
false
false
0
0
0
0
0
0
0.5
false
false
13
fbdc76dc5a4662ba144dc1664cfa7442e352281c
10,943,576,708,115
15017211930ea8199f57c1038a9f9d550420c77e
/src/main/java/com/wilkhu/keeper/SchedulerMessage.java
4b445de0c58eb1ad092157c4c54b01b51d3cd82d
[]
no_license
Wilkhu90/SpringJPAPostgres
https://github.com/Wilkhu90/SpringJPAPostgres
d27204ee7741d7bb733e41bf365fbf6eb90bc9e1
91bb84175120ec7880a50d28f86ca21e8af92517
refs/heads/master
2021-04-28T20:51:04.965000
2018-02-27T03:43:33
2018-02-27T03:43:33
121,936,105
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.wilkhu.keeper; import com.wilkhu.keeper.entity.Person; import com.wilkhu.keeper.service.PersonService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.messaging.handler.annotation.MessageMapping; import org.springframework.messaging.handler.annotation.SendTo; import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import java.util.List; @Controller public class SchedulerMessage { @Autowired private SimpMessagingTemplate template; @Autowired private PersonService personService; @MessageMapping("/hello") @SendTo("/topic/greetings") public List<Person> greeting() throws Exception{ return personService.findAll(); } @Scheduled(fixedDelay = 1000) public String test() { template.convertAndSend("/topic/greetings", personService.findAll()); return "Hel"; } }
UTF-8
Java
1,246
java
SchedulerMessage.java
Java
[]
null
[]
package com.wilkhu.keeper; import com.wilkhu.keeper.entity.Person; import com.wilkhu.keeper.service.PersonService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.messaging.handler.annotation.MessageMapping; import org.springframework.messaging.handler.annotation.SendTo; import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import java.util.List; @Controller public class SchedulerMessage { @Autowired private SimpMessagingTemplate template; @Autowired private PersonService personService; @MessageMapping("/hello") @SendTo("/topic/greetings") public List<Person> greeting() throws Exception{ return personService.findAll(); } @Scheduled(fixedDelay = 1000) public String test() { template.convertAndSend("/topic/greetings", personService.findAll()); return "Hel"; } }
1,246
0.792937
0.789727
36
33.611111
23.741991
77
false
false
0
0
0
0
0
0
0.555556
false
false
13
b4fe8bf93ac7865508ae240770db7aff1dce581d
27,539,330,328,851
790437f442a99259cc643bba4e06e1a0f5ce4f24
/Level 3 - Capstone Project 1/SaveDataIO.java
26c859fca3651c9dbc62af36cdea618dd409e0f1
[]
no_license
OM3G424747/hyperionDev_CapstoneProjects
https://github.com/OM3G424747/hyperionDev_CapstoneProjects
08ebe8cd8ceb542ca372bc08071c15d4235e76bb
2f975c8ca19d5f671a841eb1c0bd1296c8f4b8a7
refs/heads/main
2023-07-27T02:14:39.955000
2021-12-04T17:18:29
2021-12-04T17:18:29
377,286,086
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.io.FileNotFoundException; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Formatter; /** * Saved Data IO Class The methods from this are used read and write saved data * from .txt files * * @author Chris Joubert * @version 3.00, 01 September 2021 */ public class SaveDataIO { /** * * Get Saved Data Method <br> * The method returns a string containing all the contents of a table * * @param statement Statement used to query the SQL server to retrieve the saved * data for each required table * @param dataType String containing the file name to be opened * @throws SQLException if an error is encountered with SQL queries * @return String containing all the file contents / "" if the file was not * opened successfully * @since version 3.00 */ static String getSavedData(Statement statement, String dataType) throws SQLException { String stringToReturn = ""; String sqlRequest = ""; if (dataType.equals("Person")) { sqlRequest = "SELECT * FROM acc_info INNER JOIN address_info ON acc_info.address_id = address_info.address_id"; // query returns the following results // 1 = account_id // 2 = account_type // 3 = first_name // 4 = last_name // 5 = email // 6 = phone_num // 7 = address_id // 8 = address_id // 9 = country // 10 = region // 11 = city // 12 = street // 13 = post_code // stores a index values of the data to be requested for the person class int[] personDataIndex = { 2, 3, 4, 6, 5, 12, 11, 10, 9, 13, 1, 7 }; // set's default value for string to be blank // if a blank string is returned it indicates an error occurred for (int value = 0; value < personDataIndex.length; value++) { ResultSet resultSet = statement.executeQuery(sqlRequest); while (resultSet.next()) { stringToReturn += resultSet.getString(personDataIndex[value]) + "|"; } stringToReturn += "\n"; } } else if (dataType.equals("Project")) { // query returns the following results // 1 = proj_num // 2 = erf_num // 3 = address_id // 4 = due_date // 5 = finalize_date // 6 = engineer_id // 7 = manager_id // 8 = architect_id // 9 = address_id // 10 = country // 11 = region // 12 = city // 13 = street // 14 = post_code // 15 = proj_num // 16 = proj_name // 17 = build_type // 18 = cost // 19 = paid // 20 = customer_id sqlRequest = "SELECT * FROM proj_info INNER JOIN address_info ON proj_info.address_id = address_info.address_id INNER JOIN cust_info on proj_info.proj_num = cust_info.proj_num"; // set's default value for string to be blank // if a blank string is returned it indicates an error occurred int[] personDataIndex = { 1, 17, 2, 13, 12, 11, 10, 14, 18, 19, 4, 5, 7, 8, 6, 20, 16, 3 }; for (int value = 0; value < personDataIndex.length; value++) { ResultSet resultSet = statement.executeQuery(sqlRequest); while (resultSet.next()) { if (personDataIndex[value] == 4 || personDataIndex[value] == 5) { // switches date format from YYYY-MM-DD to DD-MM-YYYY String[] stringDateArray = resultSet.getString(personDataIndex[value]).split("-"); String newDateFormat = stringDateArray[2] + "-" + stringDateArray[1] + "-" + stringDateArray[0]; stringToReturn += newDateFormat + "|"; } else { stringToReturn += resultSet.getString(personDataIndex[value]) + "|"; } } stringToReturn += "\n"; } } return stringToReturn; } /** * * Set To File Method <br> * The method saves passed String array to the SQL server Array if first checked * to determine if the data is new or existing * * New Arrays are inserted into the relevant tables If the key value already * exists on a table the data is looped over and new data is set to the relevant * rows * * @param statement Statement used to pass the new values on to the SQL * server * @param stringToWrite String[] containing the data to be saved to the file * @param dataType String containing the file name to save the data to * @throws SQLException if an error is encountered with SQL queriesf * @since version 3.00 */ static void setToDatabase(Statement statement, String[] arrayToWrite, String dataType) throws SQLException { // string to check if current value already exists in DB String sqlRequestID = sqlSelect("COUNT(" + (dataType.equals("Person") ? "account_id" : "proj_num") + ")") + sqlFrom(dataType.equals("Person") ? "acc_info" : "proj_info") + sqlWhere(dataType.equals("Person") ? "account_id" : "proj_num") + " = "; // switches to true of the data is a new entry Boolean newValue = false; // appends the relevant key to the query String idCheck = sqlRequestID + arrayToWrite[0]; // confirms if passed array is a new entry or and edited entry ResultSet resultSet = statement.executeQuery(idCheck); while (resultSet.next()) { if (resultSet.getInt(1) == 0) { newValue = true; } } // adds new row to relevant personnel tables if data is new if (dataType.equals("Person") && newValue) { // Update Acc_info table statement.executeUpdate(sqlInsert("acc_info") + sqlAccValues(arrayToWrite[0], arrayToWrite[1], arrayToWrite[2], arrayToWrite[3], arrayToWrite[5], arrayToWrite[4], arrayToWrite[11])); // Update Address_info table statement.executeUpdate(sqlInsert("address_info") + sqlAddressValues(arrayToWrite[11], arrayToWrite[9], arrayToWrite[8], arrayToWrite[7], arrayToWrite[6], arrayToWrite[10])); // adds new row to relevant project tables if the data is new } else if (dataType.equals("Project") && newValue) { statement.executeUpdate( sqlInsert("proj_info") + sqlProjValues(arrayToWrite[0], arrayToWrite[2], arrayToWrite[17], arrayToWrite[10], arrayToWrite[11], arrayToWrite[14], arrayToWrite[12], arrayToWrite[13])); statement.executeUpdate(sqlInsert("cust_info") + sqlCustValues(arrayToWrite[0], arrayToWrite[16], arrayToWrite[1], arrayToWrite[8], arrayToWrite[9], arrayToWrite[15])); statement.executeUpdate(sqlInsert("address_info") + sqlAddressValues(arrayToWrite[17], arrayToWrite[6], arrayToWrite[5], arrayToWrite[4], arrayToWrite[3], arrayToWrite[7])); // if the data is not new it means it's related to an existing project / person // each relevant value is looped over and compared to existing values to // determine if change were made // any changes will replace existing values } else if (dataType.equals("Person") && !newValue) { // index values for "arrayToWrite" if set to person are: // [0] accountNum // [1] personType // [2] firstName // [3] lastName // [4] phoneNumber // [5] email // [6] street // [7] city // [8] region // [9] country // [10] postalCode // [11] addressID String[] accTableValues = { "account_type", "first_name", "last_name", "email", "phone_num" }; // stores the index of each value in the accTableValues array in the passed // "arrayToWrite" int[] accTableIndex = { 1, 2, 3, 5, 4 }; // -1 indicates no changes int[] trueAccIndex = { -1, -1 }; for (int index = 0; index < accTableValues.length; index++) { String accCheck = sqlSelect(sqlCount(accTableValues[index])) + sqlFrom("acc_info") + sqlWhere(accTableValues[index] + " = " + sqlString(arrayToWrite[accTableIndex[index]]) + " AND account_id = " + arrayToWrite[0]); resultSet = statement.executeQuery(accCheck); while (resultSet.next()) { if (resultSet.getInt(1) == 0) { if (accTableValues[index].equals("last_name")) { trueAccIndex[1] = index; } else { trueAccIndex[0] = index; } } } } // updates acc_info table if a value was found to be changed if (trueAccIndex[0] >= 0) { statement.executeUpdate(sqlUpdate("acc_info", accTableValues[trueAccIndex[0]], sqlString(arrayToWrite[accTableIndex[trueAccIndex[0]]]) + sqlWhere("account_id = " + arrayToWrite[0]))); } // updates acc_info table's last_name if it's found to be changed if (trueAccIndex[1] >= 0) { statement.executeUpdate(sqlUpdate("acc_info", accTableValues[trueAccIndex[1]], sqlString(arrayToWrite[accTableIndex[trueAccIndex[1]]]) + sqlWhere("account_id = " + arrayToWrite[0]))); } // checks for address changes on the person's account String getAddressID = sqlSelect("address_id") + sqlFrom("acc_info") + sqlWhere("account_id = " + arrayToWrite[0]); int currentAddressID = -1; resultSet = statement.executeQuery(getAddressID); while (resultSet.next()) { currentAddressID = resultSet.getInt(1); } String[] addTableValues = { "country", "region", "city", "street", "post_code" }; // stores the index of each value in the addTableValues array in the passed // "arrayToWrite" int[] addTableIndex = { 9, 8, 7, 6, 10 }; // stores the values that were found to have changed while performing the check // -1 indicates no changes int[] trueAddIndex = { -1, -1, -1, -1, -1 }; for (int index = 0; index < addTableValues.length; index++) { String addressCheck = sqlSelect(sqlCount(addTableValues[index])) + sqlFrom("address_info") + sqlWhere(addTableValues[index] + " = " + sqlString( arrayToWrite[addTableIndex[index]] + " AND address_id = " + currentAddressID)); // sets values for trueAddIndex to track current changes to selected address resultSet = statement.executeQuery(addressCheck); while (resultSet.next()) { if (resultSet.getInt(1) == 0) { trueAddIndex[index] = addTableIndex[index]; } } } for (int index = 0; index < trueAddIndex.length; index++) { if (trueAddIndex[index] >= 0) { statement.executeUpdate(sqlUpdate("address_info", addTableValues[index], sqlString(arrayToWrite[trueAddIndex[index]])) + sqlWhere("address_id") + " = " + currentAddressID); } } } else if (dataType.equals("Project") && !newValue) { // arrayToWrite index if values is set to Project // [0] projectNum // [1] buildingType // [2] erfNum // [3] street // [4] city // [5] region // [6] country // [7] postalCode // [8] totalCost // [9] totalPaid // [10] deadLine // [11] completionDate // [12] projectManager // [13] projectArchitect // [14] projectContractor // [15] projectCustomer // [16] projectName // [17] addressID // check project table for changes String[] projTableValues = { "proj_num", "erf_num", "due_date", "finalize_date", "engineer_id", "manager_id", "architect_id" }; // stores the index of each value in the projTableValues array in the passed // "arrayToWrite" int[] projTableIndex = { 0, 2, 10, 11, 14, 12, 13 }; // -1 indicates no changes int trueProjIndex = -1; for (int index = 0; index < projTableIndex.length; index++) { String projCheck = sqlSelect(sqlCount(projTableValues[index])) + sqlFrom("proj_info") + sqlWhere(projTableValues[index] + " = " + (projTableValues[index].equals("due_date") || projTableValues[index].equals("finalize_date") ? sqlToDate(arrayToWrite[projTableIndex[index]]) : arrayToWrite[projTableIndex[index]])); // checks which values changed relevant to the proj_info table resultSet = statement.executeQuery(projCheck); while (resultSet.next()) { if (resultSet.getInt(1) == 0) { trueProjIndex = index; } } } // updated proj_info table if a value was found to be changed if (trueProjIndex >= 0) { statement.executeUpdate(sqlUpdate("proj_info", projTableValues[trueProjIndex], (projTableValues[trueProjIndex].equals("due_date") || projTableValues[trueProjIndex].equals("finalize_date") ? sqlToDate(arrayToWrite[projTableIndex[trueProjIndex]]) : arrayToWrite[projTableIndex[trueProjIndex]]))); return; } // check customer table for changes String[] custTableValues = { "proj_num", "proj_name", "build_type", "cost", "paid ", "customer_id" }; // stores the index of each value in the custTableValues array in the passed // "arrayToWrite" int[] custTableIndex = { 0, 16, 1, 8, 9, 15 }; // -1 indicates no changes int trueCustIndex = -1; for (int index = 0; index < custTableValues.length; index++) { String custCheck = sqlSelect(sqlCount(custTableValues[index])) + sqlFrom("cust_info") + sqlWhere(custTableValues[index] + " = " + (custTableValues[index].equals("proj_num") || custTableValues[index].equals("customer_id") ? arrayToWrite[custTableIndex[index]] : sqlString(arrayToWrite[custTableIndex[index]]))); // confirms which changes took place relevant to the cust_info table resultSet = statement.executeQuery(custCheck); while (resultSet.next()) { if (resultSet.getInt(1) == 0) { trueCustIndex = index; } } } // updated cust_info table if a value was found to be changed if (trueCustIndex >= 0) { statement.executeUpdate(sqlUpdate("cust_info", custTableValues[trueCustIndex], (custTableValues[trueCustIndex].equals("proj_num") || custTableValues[trueCustIndex].equals("customer_id") ? arrayToWrite[custTableIndex[trueCustIndex]] : sqlString(arrayToWrite[custTableIndex[trueCustIndex]])))); return; } // checks which changes where made relevant to the address_info table String getAddressID = sqlSelect("address_id") + sqlFrom("proj_info") + sqlWhere(projTableValues[0] + " = " + arrayToWrite[0]); int currentAddressID = -1; resultSet = statement.executeQuery(getAddressID); while (resultSet.next()) { currentAddressID = resultSet.getInt(1); } String[] addTableValues = { "country", "region", "city", "street", "post_code" }; // stores the index of each value in the custTableValues array in the passed // "arrayToWrite" int[] addTableIndex = { 6, 5, 4, 3, 7 }; // array tracks different fields of table to list which had changes // -1 indicates no changes int[] trueAddIndex = { -1, -1, -1, -1, -1 }; for (int index = 0; index < addTableValues.length; index++) { String addressCheck = sqlSelect(sqlCount(addTableValues[index])) + sqlFrom("address_info") + sqlWhere(addTableValues[index] + " = " + sqlString( arrayToWrite[addTableIndex[index]] + " AND address_id = " + currentAddressID)); resultSet = statement.executeQuery(addressCheck); while (resultSet.next()) { if (resultSet.getInt(1) == 0) { trueAddIndex[index] = addTableIndex[index]; } } } for (int index = 0; index < trueAddIndex.length; index++) { if (trueAddIndex[index] >= 0) { statement.executeUpdate(sqlUpdate("address_info", addTableValues[index], sqlString(arrayToWrite[trueAddIndex[index]])) + sqlWhere("address_id") + " = " + currentAddressID); } } } } /** * * SQL Select format method <br> * Formats passed value to be correctly placed with "SELECT" syntax * * used only to improve formatting and layout of SQL queries * * * @param String selection, value to select from the database * @return correctly formatted String with passed values for * @see SaveDataIO * @since version 3.00 */ private static String sqlSelect(String selection) { return "SELECT " + selection; } /** * * SQL Update format method <br> * Formats passed value to be correctly placed with "UPDATE" syntax * * used only to improve formatting and layout of SQL queries * * * @param String table, value to select table from the database * @param String column, value to select column from the database * @param String value, value to change the current value to * @return correctly formatted String with passed values for * @see SaveDataIO * @since version 3.00 */ private static String sqlUpdate(String table, String column, String value) { return "UPDATE " + table + " SET " + column + " = " + value; } /** * * SQL Count format method <br> * Formats passed value to be correctly placed with "COUNT" syntax * * used only to improve formatting and layout of SQL queries * * * @param String selection, value to select table from the database to be * counted * @return correctly formatted String with passed values for * @see SaveDataIO * @since version 3.00 */ private static String sqlCount(String selection) { return " COUNT( " + selection + ") "; } /** * * SQL String format method <br> * Formats passed value to be correctly placed with Apostrophes for char values * or other values that require Apostrophes * * used only to improve formatting and layout of SQL queries * * * @param String value, value to be returned with apostrophes around it * @return correctly formatted String with passed values for * @see SaveDataIO * @since version 3.00 */ private static String sqlString(String value) { return " '" + value + "' "; } /** * * SQL Insert format method <br> * Formats passed value to be correctly placed with "INSERT INTO" syntax for SQL * * used only to improve formatting and layout of SQL queries * * * @param String table, value to be returned for table to be selected * @return correctly formatted String with passed values for * @see SaveDataIO * @since version 3.00 */ private static String sqlInsert(String table) { return "INSERT INTO " + table; } /** * * SQL From format method <br> * Formats passed value to be correctly placed with "FROM" syntax for SQL * * used only to improve formatting and layout of SQL queries * * * @param String table, value to be returned for selecting tables * @return correctly formatted String with passed values for * @see SaveDataIO * @since version 3.00 */ private static String sqlFrom(String table) { return " FROM " + table; } /** * * SQL Where format method <br> * Formats passed value to be correctly placed with "WHERE" syntax for SQL * * used only to improve formatting and layout of SQL queries * * * @param String selection, value to be returned for filtering queries * @return correctly formatted String with passed values for * @see SaveDataIO * @since version 3.00 */ private static String sqlWhere(String selection) { return " WHERE " + selection; } /** * * SQL toDate format method <br> * Formats passed value to be correctly placed with "STR_TO_DATE" syntax for SQL * * used only to improve formatting and layout of SQL queries * * * @param String selection, value to be returned for adding or searching a date * in the correct format * @return correctly formatted String with passed values for * @see SaveDataIO * @since version 3.00 */ private static String sqlToDate(String date) { return " STR_TO_DATE('" + date + "', '%d-%m-%Y')"; } /** * * SQL Project Values format method <br> * Formats passed value to be correctly placed in correct format and order for * inserting into proj_info table * * used only to improve formatting and layout of SQL queries * * * @param String primaryKey, contains primary key for proj_info table * @param String erfNum, contains erf number for proj_info table * @param String addressID, value containing addressID of project * @param String dueDate, value for current due date * @param String finalizeDate, value for current finalized date * @param String engineerID, contains the account ID of the engineer assigned to * the project * @param String managerID, contains the account ID of the manager assigned to * the project * @param String architectID, contains the account ID of the architect assigned * to the project * @return correctly formatted String with passed values for * @see SaveDataIO * @since version 3.00 */ private static String sqlProjValues(String primaryKey, String erfNum, String addressID, String dueDate, String finalizeDate, String engineerID, String managerID, String architectID) { String sqlValues = " VALUES (" + primaryKey + "," + erfNum + "," + addressID + "," + "" + sqlToDate(dueDate) + "," + "" + sqlToDate(finalizeDate) + "," + engineerID + "," + managerID + "," + architectID + ")"; return sqlValues; } /** * * SQL Customer Values format method <br> * Formats passed value to be correctly placed in correct format and order for * inserting into cust_info table * * used only to improve formatting and layout of SQL queries * * * @param String primaryKey, contains primary key for cust_info table * @param String projName, contains project name currently assigned to the * project * @param String buildType, value containing the current type of building * @param String cost, value for project total cost * @param String paid, value for total paid towards project so far * @param String customerID, contains the account ID of the customer assigned to * the project * @return correctly formatted String with passed values for * @see SaveDataIO * @since version 3.00 */ private static String sqlCustValues(String primaryKey, String projName, String buildType, String cost, String paid, String customerID) { String sqlValues = " VALUES (" + primaryKey + "," + "'" + projName + "'," + "'" + buildType + "'," + cost + "," + paid + "," + customerID + ")"; return sqlValues; } /** * * SQL Address Values format method <br> * Formats passed value to be correctly placed in correct format and order for * inserting into address_info table * * used only to improve formatting and layout of SQL queries * * * @param String primaryKey, contains primary key for address_info table * @param String country, contains the country associated with the project / * person * @param String region, contains the region/province associated with the * project / person * @param String city, contains the city associated with the project / person * @param String street, contains the street associated with the project / * person * @param String postalCode, contains the postal code associated with the * project / person * @return correctly formatted String with passed values for * @see SaveDataIO * @since version 3.00 */ private static String sqlAddressValues(String primaryKey, String country, String region, String city, String street, String postalCode) { String sqlValues = " VALUES (" + primaryKey + "," + "'" + country + "'," + "'" + region + "'," + "'" + city + "'," + "'" + street + "'," + "'" + postalCode + "')"; return sqlValues; } /** * * SQL Account Values format method <br> * Formats passed value to be correctly placed in correct format and order for * inserting into acc_info table * * used only to improve formatting and layout of SQL queries * * * @param String primaryKey, contains primary key for address_info table * @param String accType, contains the account type associated with the person * @param String firstName, contains the first name associated with the person * @param String lastName, contains the last name associated with the person * @param String email, contains the email associated with the person * @param String phoneNum, contains the phone number associated with the person * @param String addressID, contains the address_id key associated with the * person for the address_info table * @return correctly formatted String with passed values for * @see SaveDataIO * @since version 3.00 */ private static String sqlAccValues(String primaryKey, String accType, String firstName, String lastName, String email, String phoneNum, String addressID) { String sqlValues = " VALUES (" + primaryKey + "," + "'" + accType + "'," + "'" + firstName + "'," + "'" + lastName + "'," + "'" + email + "'," + "'" + phoneNum + "'," + addressID + ")"; return sqlValues; } /** * * New Address Key Method <br> * Queries the address_info table to get the current max address_id value to * return a new new value 1 digit higher * * @param statement Statement used to confirm the the current highest ID value * on the address_info table * @throws SQLException if an error is encountered with SQL queries * @return int newAddress ID for use with Key for ddress_info table * @since version 3.00 */ public static int getNewAddressID(Statement statement) throws SQLException { String requestLastID = sqlSelect("MAX(address_id)") + sqlFrom("address_info"); int maxID = 0; ResultSet resultSet = statement.executeQuery(requestLastID); while (resultSet.next()) { maxID = resultSet.getInt(1); } // adds 1 to generate new address ID maxID++; return maxID; } /** * * Set To File Method <br> * The method saves passed String to a .txt file with the passed name * * @param stringToWrite String containing the data to be saved to the file * @param fileName String containing the file name to save the data to * @since version 1.00 */ static void setToFile(String stringToWrite, String fileName) { Formatter file; try { file = new Formatter(fileName + ".txt"); file.format(stringToWrite); // file is closed after the data is written to the txt file file.close(); // if an error is encountered and file is not working, the method returns } catch (FileNotFoundException e) { return; } } }
UTF-8
Java
26,656
java
SaveDataIO.java
Java
[ { "context": "ite saved data\r\n * from .txt files\r\n *\r\n * @author Chris Joubert\r\n * @version 3.00, 01 September 2021\r\n */\r\n\r\npubl", "end": 291, "score": 0.9998239278793335, "start": 278, "tag": "NAME", "value": "Chris Joubert" }, { "context": "// [0] accountNum\r\n\t\t\t...
null
[]
import java.io.FileNotFoundException; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Formatter; /** * Saved Data IO Class The methods from this are used read and write saved data * from .txt files * * @author <NAME> * @version 3.00, 01 September 2021 */ public class SaveDataIO { /** * * Get Saved Data Method <br> * The method returns a string containing all the contents of a table * * @param statement Statement used to query the SQL server to retrieve the saved * data for each required table * @param dataType String containing the file name to be opened * @throws SQLException if an error is encountered with SQL queries * @return String containing all the file contents / "" if the file was not * opened successfully * @since version 3.00 */ static String getSavedData(Statement statement, String dataType) throws SQLException { String stringToReturn = ""; String sqlRequest = ""; if (dataType.equals("Person")) { sqlRequest = "SELECT * FROM acc_info INNER JOIN address_info ON acc_info.address_id = address_info.address_id"; // query returns the following results // 1 = account_id // 2 = account_type // 3 = first_name // 4 = last_name // 5 = email // 6 = phone_num // 7 = address_id // 8 = address_id // 9 = country // 10 = region // 11 = city // 12 = street // 13 = post_code // stores a index values of the data to be requested for the person class int[] personDataIndex = { 2, 3, 4, 6, 5, 12, 11, 10, 9, 13, 1, 7 }; // set's default value for string to be blank // if a blank string is returned it indicates an error occurred for (int value = 0; value < personDataIndex.length; value++) { ResultSet resultSet = statement.executeQuery(sqlRequest); while (resultSet.next()) { stringToReturn += resultSet.getString(personDataIndex[value]) + "|"; } stringToReturn += "\n"; } } else if (dataType.equals("Project")) { // query returns the following results // 1 = proj_num // 2 = erf_num // 3 = address_id // 4 = due_date // 5 = finalize_date // 6 = engineer_id // 7 = manager_id // 8 = architect_id // 9 = address_id // 10 = country // 11 = region // 12 = city // 13 = street // 14 = post_code // 15 = proj_num // 16 = proj_name // 17 = build_type // 18 = cost // 19 = paid // 20 = customer_id sqlRequest = "SELECT * FROM proj_info INNER JOIN address_info ON proj_info.address_id = address_info.address_id INNER JOIN cust_info on proj_info.proj_num = cust_info.proj_num"; // set's default value for string to be blank // if a blank string is returned it indicates an error occurred int[] personDataIndex = { 1, 17, 2, 13, 12, 11, 10, 14, 18, 19, 4, 5, 7, 8, 6, 20, 16, 3 }; for (int value = 0; value < personDataIndex.length; value++) { ResultSet resultSet = statement.executeQuery(sqlRequest); while (resultSet.next()) { if (personDataIndex[value] == 4 || personDataIndex[value] == 5) { // switches date format from YYYY-MM-DD to DD-MM-YYYY String[] stringDateArray = resultSet.getString(personDataIndex[value]).split("-"); String newDateFormat = stringDateArray[2] + "-" + stringDateArray[1] + "-" + stringDateArray[0]; stringToReturn += newDateFormat + "|"; } else { stringToReturn += resultSet.getString(personDataIndex[value]) + "|"; } } stringToReturn += "\n"; } } return stringToReturn; } /** * * Set To File Method <br> * The method saves passed String array to the SQL server Array if first checked * to determine if the data is new or existing * * New Arrays are inserted into the relevant tables If the key value already * exists on a table the data is looped over and new data is set to the relevant * rows * * @param statement Statement used to pass the new values on to the SQL * server * @param stringToWrite String[] containing the data to be saved to the file * @param dataType String containing the file name to save the data to * @throws SQLException if an error is encountered with SQL queriesf * @since version 3.00 */ static void setToDatabase(Statement statement, String[] arrayToWrite, String dataType) throws SQLException { // string to check if current value already exists in DB String sqlRequestID = sqlSelect("COUNT(" + (dataType.equals("Person") ? "account_id" : "proj_num") + ")") + sqlFrom(dataType.equals("Person") ? "acc_info" : "proj_info") + sqlWhere(dataType.equals("Person") ? "account_id" : "proj_num") + " = "; // switches to true of the data is a new entry Boolean newValue = false; // appends the relevant key to the query String idCheck = sqlRequestID + arrayToWrite[0]; // confirms if passed array is a new entry or and edited entry ResultSet resultSet = statement.executeQuery(idCheck); while (resultSet.next()) { if (resultSet.getInt(1) == 0) { newValue = true; } } // adds new row to relevant personnel tables if data is new if (dataType.equals("Person") && newValue) { // Update Acc_info table statement.executeUpdate(sqlInsert("acc_info") + sqlAccValues(arrayToWrite[0], arrayToWrite[1], arrayToWrite[2], arrayToWrite[3], arrayToWrite[5], arrayToWrite[4], arrayToWrite[11])); // Update Address_info table statement.executeUpdate(sqlInsert("address_info") + sqlAddressValues(arrayToWrite[11], arrayToWrite[9], arrayToWrite[8], arrayToWrite[7], arrayToWrite[6], arrayToWrite[10])); // adds new row to relevant project tables if the data is new } else if (dataType.equals("Project") && newValue) { statement.executeUpdate( sqlInsert("proj_info") + sqlProjValues(arrayToWrite[0], arrayToWrite[2], arrayToWrite[17], arrayToWrite[10], arrayToWrite[11], arrayToWrite[14], arrayToWrite[12], arrayToWrite[13])); statement.executeUpdate(sqlInsert("cust_info") + sqlCustValues(arrayToWrite[0], arrayToWrite[16], arrayToWrite[1], arrayToWrite[8], arrayToWrite[9], arrayToWrite[15])); statement.executeUpdate(sqlInsert("address_info") + sqlAddressValues(arrayToWrite[17], arrayToWrite[6], arrayToWrite[5], arrayToWrite[4], arrayToWrite[3], arrayToWrite[7])); // if the data is not new it means it's related to an existing project / person // each relevant value is looped over and compared to existing values to // determine if change were made // any changes will replace existing values } else if (dataType.equals("Person") && !newValue) { // index values for "arrayToWrite" if set to person are: // [0] accountNum // [1] personType // [2] firstName // [3] lastName // [4] phoneNumber // [5] email // [6] street // [7] city // [8] region // [9] country // [10] postalCode // [11] addressID String[] accTableValues = { "account_type", "first_name", "last_name", "email", "phone_num" }; // stores the index of each value in the accTableValues array in the passed // "arrayToWrite" int[] accTableIndex = { 1, 2, 3, 5, 4 }; // -1 indicates no changes int[] trueAccIndex = { -1, -1 }; for (int index = 0; index < accTableValues.length; index++) { String accCheck = sqlSelect(sqlCount(accTableValues[index])) + sqlFrom("acc_info") + sqlWhere(accTableValues[index] + " = " + sqlString(arrayToWrite[accTableIndex[index]]) + " AND account_id = " + arrayToWrite[0]); resultSet = statement.executeQuery(accCheck); while (resultSet.next()) { if (resultSet.getInt(1) == 0) { if (accTableValues[index].equals("last_name")) { trueAccIndex[1] = index; } else { trueAccIndex[0] = index; } } } } // updates acc_info table if a value was found to be changed if (trueAccIndex[0] >= 0) { statement.executeUpdate(sqlUpdate("acc_info", accTableValues[trueAccIndex[0]], sqlString(arrayToWrite[accTableIndex[trueAccIndex[0]]]) + sqlWhere("account_id = " + arrayToWrite[0]))); } // updates acc_info table's last_name if it's found to be changed if (trueAccIndex[1] >= 0) { statement.executeUpdate(sqlUpdate("acc_info", accTableValues[trueAccIndex[1]], sqlString(arrayToWrite[accTableIndex[trueAccIndex[1]]]) + sqlWhere("account_id = " + arrayToWrite[0]))); } // checks for address changes on the person's account String getAddressID = sqlSelect("address_id") + sqlFrom("acc_info") + sqlWhere("account_id = " + arrayToWrite[0]); int currentAddressID = -1; resultSet = statement.executeQuery(getAddressID); while (resultSet.next()) { currentAddressID = resultSet.getInt(1); } String[] addTableValues = { "country", "region", "city", "street", "post_code" }; // stores the index of each value in the addTableValues array in the passed // "arrayToWrite" int[] addTableIndex = { 9, 8, 7, 6, 10 }; // stores the values that were found to have changed while performing the check // -1 indicates no changes int[] trueAddIndex = { -1, -1, -1, -1, -1 }; for (int index = 0; index < addTableValues.length; index++) { String addressCheck = sqlSelect(sqlCount(addTableValues[index])) + sqlFrom("address_info") + sqlWhere(addTableValues[index] + " = " + sqlString( arrayToWrite[addTableIndex[index]] + " AND address_id = " + currentAddressID)); // sets values for trueAddIndex to track current changes to selected address resultSet = statement.executeQuery(addressCheck); while (resultSet.next()) { if (resultSet.getInt(1) == 0) { trueAddIndex[index] = addTableIndex[index]; } } } for (int index = 0; index < trueAddIndex.length; index++) { if (trueAddIndex[index] >= 0) { statement.executeUpdate(sqlUpdate("address_info", addTableValues[index], sqlString(arrayToWrite[trueAddIndex[index]])) + sqlWhere("address_id") + " = " + currentAddressID); } } } else if (dataType.equals("Project") && !newValue) { // arrayToWrite index if values is set to Project // [0] projectNum // [1] buildingType // [2] erfNum // [3] street // [4] city // [5] region // [6] country // [7] postalCode // [8] totalCost // [9] totalPaid // [10] deadLine // [11] completionDate // [12] projectManager // [13] projectArchitect // [14] projectContractor // [15] projectCustomer // [16] projectName // [17] addressID // check project table for changes String[] projTableValues = { "proj_num", "erf_num", "due_date", "finalize_date", "engineer_id", "manager_id", "architect_id" }; // stores the index of each value in the projTableValues array in the passed // "arrayToWrite" int[] projTableIndex = { 0, 2, 10, 11, 14, 12, 13 }; // -1 indicates no changes int trueProjIndex = -1; for (int index = 0; index < projTableIndex.length; index++) { String projCheck = sqlSelect(sqlCount(projTableValues[index])) + sqlFrom("proj_info") + sqlWhere(projTableValues[index] + " = " + (projTableValues[index].equals("due_date") || projTableValues[index].equals("finalize_date") ? sqlToDate(arrayToWrite[projTableIndex[index]]) : arrayToWrite[projTableIndex[index]])); // checks which values changed relevant to the proj_info table resultSet = statement.executeQuery(projCheck); while (resultSet.next()) { if (resultSet.getInt(1) == 0) { trueProjIndex = index; } } } // updated proj_info table if a value was found to be changed if (trueProjIndex >= 0) { statement.executeUpdate(sqlUpdate("proj_info", projTableValues[trueProjIndex], (projTableValues[trueProjIndex].equals("due_date") || projTableValues[trueProjIndex].equals("finalize_date") ? sqlToDate(arrayToWrite[projTableIndex[trueProjIndex]]) : arrayToWrite[projTableIndex[trueProjIndex]]))); return; } // check customer table for changes String[] custTableValues = { "proj_num", "proj_name", "build_type", "cost", "paid ", "customer_id" }; // stores the index of each value in the custTableValues array in the passed // "arrayToWrite" int[] custTableIndex = { 0, 16, 1, 8, 9, 15 }; // -1 indicates no changes int trueCustIndex = -1; for (int index = 0; index < custTableValues.length; index++) { String custCheck = sqlSelect(sqlCount(custTableValues[index])) + sqlFrom("cust_info") + sqlWhere(custTableValues[index] + " = " + (custTableValues[index].equals("proj_num") || custTableValues[index].equals("customer_id") ? arrayToWrite[custTableIndex[index]] : sqlString(arrayToWrite[custTableIndex[index]]))); // confirms which changes took place relevant to the cust_info table resultSet = statement.executeQuery(custCheck); while (resultSet.next()) { if (resultSet.getInt(1) == 0) { trueCustIndex = index; } } } // updated cust_info table if a value was found to be changed if (trueCustIndex >= 0) { statement.executeUpdate(sqlUpdate("cust_info", custTableValues[trueCustIndex], (custTableValues[trueCustIndex].equals("proj_num") || custTableValues[trueCustIndex].equals("customer_id") ? arrayToWrite[custTableIndex[trueCustIndex]] : sqlString(arrayToWrite[custTableIndex[trueCustIndex]])))); return; } // checks which changes where made relevant to the address_info table String getAddressID = sqlSelect("address_id") + sqlFrom("proj_info") + sqlWhere(projTableValues[0] + " = " + arrayToWrite[0]); int currentAddressID = -1; resultSet = statement.executeQuery(getAddressID); while (resultSet.next()) { currentAddressID = resultSet.getInt(1); } String[] addTableValues = { "country", "region", "city", "street", "post_code" }; // stores the index of each value in the custTableValues array in the passed // "arrayToWrite" int[] addTableIndex = { 6, 5, 4, 3, 7 }; // array tracks different fields of table to list which had changes // -1 indicates no changes int[] trueAddIndex = { -1, -1, -1, -1, -1 }; for (int index = 0; index < addTableValues.length; index++) { String addressCheck = sqlSelect(sqlCount(addTableValues[index])) + sqlFrom("address_info") + sqlWhere(addTableValues[index] + " = " + sqlString( arrayToWrite[addTableIndex[index]] + " AND address_id = " + currentAddressID)); resultSet = statement.executeQuery(addressCheck); while (resultSet.next()) { if (resultSet.getInt(1) == 0) { trueAddIndex[index] = addTableIndex[index]; } } } for (int index = 0; index < trueAddIndex.length; index++) { if (trueAddIndex[index] >= 0) { statement.executeUpdate(sqlUpdate("address_info", addTableValues[index], sqlString(arrayToWrite[trueAddIndex[index]])) + sqlWhere("address_id") + " = " + currentAddressID); } } } } /** * * SQL Select format method <br> * Formats passed value to be correctly placed with "SELECT" syntax * * used only to improve formatting and layout of SQL queries * * * @param String selection, value to select from the database * @return correctly formatted String with passed values for * @see SaveDataIO * @since version 3.00 */ private static String sqlSelect(String selection) { return "SELECT " + selection; } /** * * SQL Update format method <br> * Formats passed value to be correctly placed with "UPDATE" syntax * * used only to improve formatting and layout of SQL queries * * * @param String table, value to select table from the database * @param String column, value to select column from the database * @param String value, value to change the current value to * @return correctly formatted String with passed values for * @see SaveDataIO * @since version 3.00 */ private static String sqlUpdate(String table, String column, String value) { return "UPDATE " + table + " SET " + column + " = " + value; } /** * * SQL Count format method <br> * Formats passed value to be correctly placed with "COUNT" syntax * * used only to improve formatting and layout of SQL queries * * * @param String selection, value to select table from the database to be * counted * @return correctly formatted String with passed values for * @see SaveDataIO * @since version 3.00 */ private static String sqlCount(String selection) { return " COUNT( " + selection + ") "; } /** * * SQL String format method <br> * Formats passed value to be correctly placed with Apostrophes for char values * or other values that require Apostrophes * * used only to improve formatting and layout of SQL queries * * * @param String value, value to be returned with apostrophes around it * @return correctly formatted String with passed values for * @see SaveDataIO * @since version 3.00 */ private static String sqlString(String value) { return " '" + value + "' "; } /** * * SQL Insert format method <br> * Formats passed value to be correctly placed with "INSERT INTO" syntax for SQL * * used only to improve formatting and layout of SQL queries * * * @param String table, value to be returned for table to be selected * @return correctly formatted String with passed values for * @see SaveDataIO * @since version 3.00 */ private static String sqlInsert(String table) { return "INSERT INTO " + table; } /** * * SQL From format method <br> * Formats passed value to be correctly placed with "FROM" syntax for SQL * * used only to improve formatting and layout of SQL queries * * * @param String table, value to be returned for selecting tables * @return correctly formatted String with passed values for * @see SaveDataIO * @since version 3.00 */ private static String sqlFrom(String table) { return " FROM " + table; } /** * * SQL Where format method <br> * Formats passed value to be correctly placed with "WHERE" syntax for SQL * * used only to improve formatting and layout of SQL queries * * * @param String selection, value to be returned for filtering queries * @return correctly formatted String with passed values for * @see SaveDataIO * @since version 3.00 */ private static String sqlWhere(String selection) { return " WHERE " + selection; } /** * * SQL toDate format method <br> * Formats passed value to be correctly placed with "STR_TO_DATE" syntax for SQL * * used only to improve formatting and layout of SQL queries * * * @param String selection, value to be returned for adding or searching a date * in the correct format * @return correctly formatted String with passed values for * @see SaveDataIO * @since version 3.00 */ private static String sqlToDate(String date) { return " STR_TO_DATE('" + date + "', '%d-%m-%Y')"; } /** * * SQL Project Values format method <br> * Formats passed value to be correctly placed in correct format and order for * inserting into proj_info table * * used only to improve formatting and layout of SQL queries * * * @param String primaryKey, contains primary key for proj_info table * @param String erfNum, contains erf number for proj_info table * @param String addressID, value containing addressID of project * @param String dueDate, value for current due date * @param String finalizeDate, value for current finalized date * @param String engineerID, contains the account ID of the engineer assigned to * the project * @param String managerID, contains the account ID of the manager assigned to * the project * @param String architectID, contains the account ID of the architect assigned * to the project * @return correctly formatted String with passed values for * @see SaveDataIO * @since version 3.00 */ private static String sqlProjValues(String primaryKey, String erfNum, String addressID, String dueDate, String finalizeDate, String engineerID, String managerID, String architectID) { String sqlValues = " VALUES (" + primaryKey + "," + erfNum + "," + addressID + "," + "" + sqlToDate(dueDate) + "," + "" + sqlToDate(finalizeDate) + "," + engineerID + "," + managerID + "," + architectID + ")"; return sqlValues; } /** * * SQL Customer Values format method <br> * Formats passed value to be correctly placed in correct format and order for * inserting into cust_info table * * used only to improve formatting and layout of SQL queries * * * @param String primaryKey, contains primary key for cust_info table * @param String projName, contains project name currently assigned to the * project * @param String buildType, value containing the current type of building * @param String cost, value for project total cost * @param String paid, value for total paid towards project so far * @param String customerID, contains the account ID of the customer assigned to * the project * @return correctly formatted String with passed values for * @see SaveDataIO * @since version 3.00 */ private static String sqlCustValues(String primaryKey, String projName, String buildType, String cost, String paid, String customerID) { String sqlValues = " VALUES (" + primaryKey + "," + "'" + projName + "'," + "'" + buildType + "'," + cost + "," + paid + "," + customerID + ")"; return sqlValues; } /** * * SQL Address Values format method <br> * Formats passed value to be correctly placed in correct format and order for * inserting into address_info table * * used only to improve formatting and layout of SQL queries * * * @param String primaryKey, contains primary key for address_info table * @param String country, contains the country associated with the project / * person * @param String region, contains the region/province associated with the * project / person * @param String city, contains the city associated with the project / person * @param String street, contains the street associated with the project / * person * @param String postalCode, contains the postal code associated with the * project / person * @return correctly formatted String with passed values for * @see SaveDataIO * @since version 3.00 */ private static String sqlAddressValues(String primaryKey, String country, String region, String city, String street, String postalCode) { String sqlValues = " VALUES (" + primaryKey + "," + "'" + country + "'," + "'" + region + "'," + "'" + city + "'," + "'" + street + "'," + "'" + postalCode + "')"; return sqlValues; } /** * * SQL Account Values format method <br> * Formats passed value to be correctly placed in correct format and order for * inserting into acc_info table * * used only to improve formatting and layout of SQL queries * * * @param String primaryKey, contains primary key for address_info table * @param String accType, contains the account type associated with the person * @param String firstName, contains the first name associated with the person * @param String lastName, contains the last name associated with the person * @param String email, contains the email associated with the person * @param String phoneNum, contains the phone number associated with the person * @param String addressID, contains the address_id key associated with the * person for the address_info table * @return correctly formatted String with passed values for * @see SaveDataIO * @since version 3.00 */ private static String sqlAccValues(String primaryKey, String accType, String firstName, String lastName, String email, String phoneNum, String addressID) { String sqlValues = " VALUES (" + primaryKey + "," + "'" + accType + "'," + "'" + firstName + "'," + "'" + lastName + "'," + "'" + email + "'," + "'" + phoneNum + "'," + addressID + ")"; return sqlValues; } /** * * New Address Key Method <br> * Queries the address_info table to get the current max address_id value to * return a new new value 1 digit higher * * @param statement Statement used to confirm the the current highest ID value * on the address_info table * @throws SQLException if an error is encountered with SQL queries * @return int newAddress ID for use with Key for ddress_info table * @since version 3.00 */ public static int getNewAddressID(Statement statement) throws SQLException { String requestLastID = sqlSelect("MAX(address_id)") + sqlFrom("address_info"); int maxID = 0; ResultSet resultSet = statement.executeQuery(requestLastID); while (resultSet.next()) { maxID = resultSet.getInt(1); } // adds 1 to generate new address ID maxID++; return maxID; } /** * * Set To File Method <br> * The method saves passed String to a .txt file with the passed name * * @param stringToWrite String containing the data to be saved to the file * @param fileName String containing the file name to save the data to * @since version 1.00 */ static void setToFile(String stringToWrite, String fileName) { Formatter file; try { file = new Formatter(fileName + ".txt"); file.format(stringToWrite); // file is closed after the data is written to the txt file file.close(); // if an error is encountered and file is not working, the method returns } catch (FileNotFoundException e) { return; } } }
26,649
0.643195
0.63029
789
31.784538
30.945665
180
false
false
0
0
0
0
0
0
2.456274
false
false
13
6c09f1293e154b1492b72f964c72f07ae8e3dd24
8,134,668,084,356
c7907f09aed70ec7609808f40e44f049c25551e2
/src/jehc/zxmodules/dao/impl/ZxExpressdeliveryDaoImpl.java
5c0215607f85195524327ddbb968c8c1dc9d101f
[]
no_license
aw12sds/zxerp
https://github.com/aw12sds/zxerp
e95bc46cc224b5548ab959156c04bfa7c7255c50
bc67c8aba9773b7d70ced9cb9277c3836396453a
refs/heads/master
2021-09-03T03:49:00.725000
2018-01-05T09:08:36
2018-01-05T09:08:36
115,586,688
0
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package jehc.zxmodules.dao.impl; import java.util.List; import java.util.Map; import org.springframework.stereotype.Repository; import jehc.xtmodules.xtcore.base.impl.BaseDaoImpl; import jehc.zxmodules.dao.ZxExpressdeliveryDao; import jehc.zxmodules.model.ZxExpressdelivery; /** * 快递邮寄 * 2017-11-24 13:10:10 陈运芝 */ @Repository("zxExpressdeliveryDao") public class ZxExpressdeliveryDaoImpl extends BaseDaoImpl implements ZxExpressdeliveryDao{ /** * 分页 * @param condition * @return */ @SuppressWarnings("unchecked") public List<ZxExpressdelivery> getZxExpressdeliveryListByCondition(Map<String,Object> condition){ return (List<ZxExpressdelivery>)this.getList("getZxExpressdeliveryListByCondition",condition); } /** * 查询对象 * @param id * @return */ public ZxExpressdelivery getZxExpressdeliveryById(String id){ return (ZxExpressdelivery)this.get("getZxExpressdeliveryById", id); } /** * 添加 * @param zx_expressdelivery * @return */ public int addZxExpressdelivery(ZxExpressdelivery zxExpressdelivery){ return this.add("addZxExpressdelivery", zxExpressdelivery); } /** * 修改 * @param zx_expressdelivery * @return */ public int updateZxExpressdelivery(ZxExpressdelivery zxExpressdelivery){ return this.update("updateZxExpressdelivery", zxExpressdelivery); } /** * 修改(根据动态条件) * @param zx_expressdelivery * @return */ public int updateZxExpressdeliveryBySelective(ZxExpressdelivery zxExpressdelivery){ return this.update("updateZxExpressdeliveryBySelective", zxExpressdelivery); } /** * 删除 * @param condition * @return */ public int delZxExpressdelivery(Map<String,Object> condition){ return this.del("delZxExpressdelivery", condition); } /** * 批量添加 * @param zx_expressdeliveryList * @return */ public int addBatchZxExpressdelivery(List<ZxExpressdelivery> zxExpressdeliveryList){ return this.add("addBatchZxExpressdelivery", zxExpressdeliveryList); } /** * 批量修改 * @param zx_expressdeliveryList * @return */ public int updateBatchZxExpressdelivery(List<ZxExpressdelivery> zxExpressdeliveryList){ return this.update("updateBatchZxExpressdelivery", zxExpressdeliveryList); } /** * 批量修改(根据动态条件) * @param zx_expressdeliveryList * @return */ public int updateBatchZxExpressdeliveryBySelective(List<ZxExpressdelivery> zxExpressdeliveryList){ return this.update("updateBatchZxExpressdeliveryBySelective", zxExpressdeliveryList); } }
UTF-8
Java
2,508
java
ZxExpressdeliveryDaoImpl.java
Java
[ { "context": "ressdelivery;\n\n/**\n* 快递邮寄 \n* 2017-11-24 13:10:10 陈运芝\n*/\n@Repository(\"zxExpressdeliveryDao\")\npublic cla", "end": 314, "score": 0.9990127086639404, "start": 311, "tag": "NAME", "value": "陈运芝" } ]
null
[]
package jehc.zxmodules.dao.impl; import java.util.List; import java.util.Map; import org.springframework.stereotype.Repository; import jehc.xtmodules.xtcore.base.impl.BaseDaoImpl; import jehc.zxmodules.dao.ZxExpressdeliveryDao; import jehc.zxmodules.model.ZxExpressdelivery; /** * 快递邮寄 * 2017-11-24 13:10:10 陈运芝 */ @Repository("zxExpressdeliveryDao") public class ZxExpressdeliveryDaoImpl extends BaseDaoImpl implements ZxExpressdeliveryDao{ /** * 分页 * @param condition * @return */ @SuppressWarnings("unchecked") public List<ZxExpressdelivery> getZxExpressdeliveryListByCondition(Map<String,Object> condition){ return (List<ZxExpressdelivery>)this.getList("getZxExpressdeliveryListByCondition",condition); } /** * 查询对象 * @param id * @return */ public ZxExpressdelivery getZxExpressdeliveryById(String id){ return (ZxExpressdelivery)this.get("getZxExpressdeliveryById", id); } /** * 添加 * @param zx_expressdelivery * @return */ public int addZxExpressdelivery(ZxExpressdelivery zxExpressdelivery){ return this.add("addZxExpressdelivery", zxExpressdelivery); } /** * 修改 * @param zx_expressdelivery * @return */ public int updateZxExpressdelivery(ZxExpressdelivery zxExpressdelivery){ return this.update("updateZxExpressdelivery", zxExpressdelivery); } /** * 修改(根据动态条件) * @param zx_expressdelivery * @return */ public int updateZxExpressdeliveryBySelective(ZxExpressdelivery zxExpressdelivery){ return this.update("updateZxExpressdeliveryBySelective", zxExpressdelivery); } /** * 删除 * @param condition * @return */ public int delZxExpressdelivery(Map<String,Object> condition){ return this.del("delZxExpressdelivery", condition); } /** * 批量添加 * @param zx_expressdeliveryList * @return */ public int addBatchZxExpressdelivery(List<ZxExpressdelivery> zxExpressdeliveryList){ return this.add("addBatchZxExpressdelivery", zxExpressdeliveryList); } /** * 批量修改 * @param zx_expressdeliveryList * @return */ public int updateBatchZxExpressdelivery(List<ZxExpressdelivery> zxExpressdeliveryList){ return this.update("updateBatchZxExpressdelivery", zxExpressdeliveryList); } /** * 批量修改(根据动态条件) * @param zx_expressdeliveryList * @return */ public int updateBatchZxExpressdeliveryBySelective(List<ZxExpressdelivery> zxExpressdeliveryList){ return this.update("updateBatchZxExpressdeliveryBySelective", zxExpressdeliveryList); } }
2,508
0.772199
0.76639
88
26.386364
29.880608
99
false
false
0
0
0
0
0
0
1.238636
false
false
13
8bf95a81d719916ca06d53b6d7b5c24704df9b09
28,003,186,796,092
7ff784363835346e94bcdd287a67f5fc3e6bae2f
/Android/BluethFish Control de Acuarios/src/com/pfc/bluethfish/control/acuarios/library/plant/PlantDetailActivity.java
34a42fdaecd0340646eb4e65300aa9da22082ee8
[]
no_license
gladielf/BluethFish-Control-de-Acuarios
https://github.com/gladielf/BluethFish-Control-de-Acuarios
a27ef78e5bdad63fc8af249e97f65ca3614553f4
f6007d36367712f8efffb6089dfc6b03ae7dd83a
refs/heads/master
2021-01-21T11:39:27.002000
2015-12-08T11:43:07
2015-12-08T11:43:07
32,079,292
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.pfc.bluethfish.control.acuarios.library.plant; import com.pfc.bluethfish.control.acuarios.data.DatabaseAdapter; import com.pfc.bluethfish.control.acuarios.R; import android.app.ActionBar; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.DialogInterface.OnClickListener; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.support.v4.app.NavUtils; import android.view.Menu; import android.view.MenuItem; /** * @author Fermín Conejo * */ public class PlantDetailActivity extends FragmentActivity { DatabaseAdapter dbAdapter; @Override protected void onCreate(Bundle savedInstanceState) { if (dbAdapter!=null){ dbAdapter.close(); } super.onCreate(savedInstanceState); setContentView(R.layout.activity_plant_detail); ActionBar actionBar = getActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setTitle(getString(R.string.action_bar_plant_library_plant_detail)); if (savedInstanceState == null) { Bundle arguments = new Bundle(); arguments.putString(PlantDetailFragment.ARG_ITEM_ID, getIntent().getStringExtra(PlantDetailFragment.ARG_ITEM_ID)); PlantDetailFragment fragment = new PlantDetailFragment(); fragment.setArguments(arguments); getSupportFragmentManager().beginTransaction() .add(R.id.plant_detail_container, fragment) .commit(); } } @Override public void onPause(){ if (dbAdapter !=null){ dbAdapter.close(); } super.onPause(); } @Override public void onStop(){ if (dbAdapter !=null){ dbAdapter.close(); } super.onStop(); } @Override public void onDestroy(){ if (dbAdapter !=null){ dbAdapter.close(); } super.onDestroy(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_about: new AlertDialog.Builder(this).setTitle(getResources() .getString(R.string.dialog_title_about)) .setMessage(R.string.dialog_message_about) .setPositiveButton(R.string.button_accept,new OnClickListener() { public void onClick(DialogInterface dialog,int arg1){ } }).show(); return true; case android.R.id.home: NavUtils.navigateUpTo(this, new Intent(this, PlantListActivity.class)); return true; default: return super.onOptionsItemSelected(item); } } }
UTF-8
Java
2,742
java
PlantDetailActivity.java
Java
[ { "context": "enu;\nimport android.view.MenuItem;\n\n/**\n * @author Fermín Conejo\n *\n */\n\npublic class PlantDetailActivity extends ", "end": 560, "score": 0.9998703598976135, "start": 547, "tag": "NAME", "value": "Fermín Conejo" } ]
null
[]
package com.pfc.bluethfish.control.acuarios.library.plant; import com.pfc.bluethfish.control.acuarios.data.DatabaseAdapter; import com.pfc.bluethfish.control.acuarios.R; import android.app.ActionBar; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.DialogInterface.OnClickListener; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.support.v4.app.NavUtils; import android.view.Menu; import android.view.MenuItem; /** * @author <NAME> * */ public class PlantDetailActivity extends FragmentActivity { DatabaseAdapter dbAdapter; @Override protected void onCreate(Bundle savedInstanceState) { if (dbAdapter!=null){ dbAdapter.close(); } super.onCreate(savedInstanceState); setContentView(R.layout.activity_plant_detail); ActionBar actionBar = getActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setTitle(getString(R.string.action_bar_plant_library_plant_detail)); if (savedInstanceState == null) { Bundle arguments = new Bundle(); arguments.putString(PlantDetailFragment.ARG_ITEM_ID, getIntent().getStringExtra(PlantDetailFragment.ARG_ITEM_ID)); PlantDetailFragment fragment = new PlantDetailFragment(); fragment.setArguments(arguments); getSupportFragmentManager().beginTransaction() .add(R.id.plant_detail_container, fragment) .commit(); } } @Override public void onPause(){ if (dbAdapter !=null){ dbAdapter.close(); } super.onPause(); } @Override public void onStop(){ if (dbAdapter !=null){ dbAdapter.close(); } super.onStop(); } @Override public void onDestroy(){ if (dbAdapter !=null){ dbAdapter.close(); } super.onDestroy(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_about: new AlertDialog.Builder(this).setTitle(getResources() .getString(R.string.dialog_title_about)) .setMessage(R.string.dialog_message_about) .setPositiveButton(R.string.button_accept,new OnClickListener() { public void onClick(DialogInterface dialog,int arg1){ } }).show(); return true; case android.R.id.home: NavUtils.navigateUpTo(this, new Intent(this, PlantListActivity.class)); return true; default: return super.onOptionsItemSelected(item); } } }
2,734
0.682233
0.681138
104
25.35577
22.445625
86
false
false
0
0
0
0
0
0
1.355769
false
false
13
78ee986542ed4415e2264011c83f09214c849f16
29,987,461,686,456
f447713e82acc3d438122c57685bd4fe355638a3
/Memento/src/memento/CarritoOpciones.java
f52d908ab179bfa0b8780368973fd8f89f58e5ea
[]
no_license
Richardial/Patrones-de-dise-o
https://github.com/Richardial/Patrones-de-dise-o
a839b9a5b4cc7a1bad86177f5ced881b078a7fce
11b02cf23de1678e8f0974f1b0d97795c615ef74
refs/heads/master
2023-01-19T09:15:53.962000
2020-11-26T19:00:02
2020-11-26T19:00:02
316,314,990
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package memento; import java.util.ArrayList; import java.util.List; /** * * @author wolve */ public class CarritoOpciones { protected List<OpcionVehiculo> opciones= new ArrayList<OpcionVehiculo>(); public Memento agregaOpcion(OpcionVehiculo opcionVehiculo) { MementoImpl resultado = new MementoImpl(); resultado.setEstado(opciones); opciones.removeAll(opcionVehiculo.getOpcionesIncompatibles()); opciones.add(opcionVehiculo); return resultado; } public void anula(Memento memento) { MementoImpl mementoImplInstance; try { mementoImplInstance = (MementoImpl) memento; } catch (ClassCastException e) { return; } opciones = mementoImplInstance.getEstado(); } public void visualiza() { System.out.println("Contenido del carrito de opciones"); for (OpcionVehiculo opcion : opciones) { opcion.visualiza(); } System.out.println(); } }
UTF-8
Java
1,199
java
CarritoOpciones.java
Java
[ { "context": "rayList;\nimport java.util.List;\n\n/**\n *\n * @author wolve\n */\npublic class CarritoOpciones {\n\n protected", "end": 278, "score": 0.9995933771133423, "start": 273, "tag": "USERNAME", "value": "wolve" } ]
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package memento; import java.util.ArrayList; import java.util.List; /** * * @author wolve */ public class CarritoOpciones { protected List<OpcionVehiculo> opciones= new ArrayList<OpcionVehiculo>(); public Memento agregaOpcion(OpcionVehiculo opcionVehiculo) { MementoImpl resultado = new MementoImpl(); resultado.setEstado(opciones); opciones.removeAll(opcionVehiculo.getOpcionesIncompatibles()); opciones.add(opcionVehiculo); return resultado; } public void anula(Memento memento) { MementoImpl mementoImplInstance; try { mementoImplInstance = (MementoImpl) memento; } catch (ClassCastException e) { return; } opciones = mementoImplInstance.getEstado(); } public void visualiza() { System.out.println("Contenido del carrito de opciones"); for (OpcionVehiculo opcion : opciones) { opcion.visualiza(); } System.out.println(); } }
1,199
0.658048
0.658048
45
25.644444
23.705748
79
false
false
0
0
0
0
0
0
0.422222
false
false
13
d21f074d71766c90361cf60ad2b0fb7fca2d20d4
11,665,131,208,323
2714534e3d766978dc6b7b0a94ce243a4e64acf7
/src/main/java/fr/esiea/nourby_leborgne/gameEngine/Main.java
2357374a5c52fa0d94c8d1d68d7376803db9ea1a
[]
no_license
Yezekael/TP4A_Letter_Game
https://github.com/Yezekael/TP4A_Letter_Game
7b0387d587168996fb0f5395fa456c2162085942
0cf1d2993e5e6905be67c2ba48909aa39833b273
refs/heads/master
2021-01-21T09:53:45.785000
2017-03-03T19:52:23
2017-03-03T19:52:23
83,344,092
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package fr.esiea.nourby_leborgne.gameEngine; public class Main { public static void main(String[] args){ Start launcher = new Start(); launcher.launch(); System.exit(0); } }
UTF-8
Java
210
java
Main.java
Java
[]
null
[]
package fr.esiea.nourby_leborgne.gameEngine; public class Main { public static void main(String[] args){ Start launcher = new Start(); launcher.launch(); System.exit(0); } }
210
0.614286
0.609524
11
17.09091
16.560932
44
false
false
0
0
0
0
0
0
1.090909
false
false
13
b80f9336e328178d654a91f3d5e8182ad631cb45
17,798,344,506,244
c982cc9e8805c1aa9ab9338bbb1bdaa418f10fee
/src/java/Controlador/Crear_Nuevo_Estudiante.java
7f4cdfc3059d5cc8eab4efc7ee443416e8a994ca
[]
no_license
BrayanRinconMendoza/Sistema-de-notas-JPA
https://github.com/BrayanRinconMendoza/Sistema-de-notas-JPA
ff4ce6b15dd744fbb5059ea698ff315b6a4b56d1
a3dfca7b60f2ed5bb1d5afa725e18b4f3aa0991a
refs/heads/master
2021-01-02T01:58:47.972000
2020-02-10T06:45:20
2020-02-10T06:45:20
239,444,668
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Controlador; import Modelo.Estudiante; import Modelo.MateriaEstudiante; import Negocio.SistemaNotas; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author Romario */ public class Crear_Nuevo_Estudiante extends HttpServlet { /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { SistemaNotas sistema=new SistemaNotas(); String codigoMateria=(String)request.getSession().getAttribute("codigoMateria"); String codigoEstudiante=request.getParameter("codigo-estudiante"); String nombreEstudiante=request.getParameter("nombre-estudiante"); String emailEstudiante=request.getParameter("email-estudiante"); String telefonoEstudiante=request.getParameter("telefono-estudiante"); String password=sistema.generarPassword(codigoEstudiante); Estudiante estudiante=new Estudiante(codigoEstudiante, nombreEstudiante, emailEstudiante, telefonoEstudiante, password); if(sistema.insertarEstudiante(estudiante)){ MateriaEstudiante me=new MateriaEstudiante(sistema.buscarEstudiante(codigoEstudiante), sistema.buscarMateria(codigoMateria)); sistema.enviarEmailPassword(password, emailEstudiante); if(sistema.insertarMateriaEstudiante(me)){ request.getSession().setAttribute("codigoMateria", codigoMateria); request.getRequestDispatcher("./Vista/VistaMateria.jsp").forward(request, response); }else{ request.getSession().setAttribute("codigoMateria", codigoMateria); request.getRequestDispatcher("./Vista/ErrorAgregarEstudiante.jsp").forward(request, response); } }else{ request.getSession().setAttribute("codigoMateria", codigoMateria); request.getRequestDispatcher("./Vista/ErrorAgregarEstudiante.jsp").forward(request, response); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
UTF-8
Java
4,054
java
Crear_Nuevo_Estudiante.java
Java
[ { "context": "t.http.HttpServletResponse;\r\n\r\n/**\r\n *\r\n * @author Romario\r\n */\r\npublic class Crear_Nuevo_Estudiante extends H", "end": 569, "score": 0.8859189748764038, "start": 562, "tag": "NAME", "value": "Romario" } ]
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Controlador; import Modelo.Estudiante; import Modelo.MateriaEstudiante; import Negocio.SistemaNotas; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author Romario */ public class Crear_Nuevo_Estudiante extends HttpServlet { /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { SistemaNotas sistema=new SistemaNotas(); String codigoMateria=(String)request.getSession().getAttribute("codigoMateria"); String codigoEstudiante=request.getParameter("codigo-estudiante"); String nombreEstudiante=request.getParameter("nombre-estudiante"); String emailEstudiante=request.getParameter("email-estudiante"); String telefonoEstudiante=request.getParameter("telefono-estudiante"); String password=sistema.generarPassword(codigoEstudiante); Estudiante estudiante=new Estudiante(codigoEstudiante, nombreEstudiante, emailEstudiante, telefonoEstudiante, password); if(sistema.insertarEstudiante(estudiante)){ MateriaEstudiante me=new MateriaEstudiante(sistema.buscarEstudiante(codigoEstudiante), sistema.buscarMateria(codigoMateria)); sistema.enviarEmailPassword(password, emailEstudiante); if(sistema.insertarMateriaEstudiante(me)){ request.getSession().setAttribute("codigoMateria", codigoMateria); request.getRequestDispatcher("./Vista/VistaMateria.jsp").forward(request, response); }else{ request.getSession().setAttribute("codigoMateria", codigoMateria); request.getRequestDispatcher("./Vista/ErrorAgregarEstudiante.jsp").forward(request, response); } }else{ request.getSession().setAttribute("codigoMateria", codigoMateria); request.getRequestDispatcher("./Vista/ErrorAgregarEstudiante.jsp").forward(request, response); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
4,054
0.684509
0.684509
100
38.540001
33.23204
137
false
false
0
0
0
0
0
0
0.52
false
false
13
86d371ec29bc10ef5c01e0482160310c74efc112
24,799,141,197,956
cfa21113b655026677aa100aa9787a5ab9227c55
/src/main/java/cn/test/app/spider/yqgov/task/ScheduleTask.java
b3b44135bcfa87fba4fa4243bb064e5f0fefc7ad
[]
no_license
yundanfeng/ycspider
https://github.com/yundanfeng/ycspider
7c2e2ae38c65191fc469ab4093642696a777e673
7defeeb6cbd2b92f27ed0f7e643416926e39f054
refs/heads/master
2021-06-19T01:30:24.816000
2019-05-31T07:59:26
2019-05-31T07:59:26
189,553,153
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.test.app.spider.yqgov.task; import javax.annotation.Resource; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; /** * @remark * @author luzh * @createTime 2017年7月5日 下午4:16:44 */ @Component public class ScheduleTask { @Resource private AsyncTask task; // 每个小时更新一次新闻列表 @Scheduled(cron = "0 0 * * * *") public void getColumnItems() { task.getColumnItems(); } @Scheduled(cron = "0 0/10 * * * *") public void crawlArticles () { task.crawlArticles(); } @Scheduled(cron = "0 0/10 * * * ?") public void pushToHomed() { task.pushToHomed(); } }
UTF-8
Java
676
java
ScheduleTask.java
Java
[ { "context": ".stereotype.Component;\n\n/** \n * @remark\n * @author luzh \n * @createTime 2017年7月5日 下午4:16:44\n */\n@Componen", "end": 216, "score": 0.9996752142906189, "start": 212, "tag": "USERNAME", "value": "luzh" } ]
null
[]
package cn.test.app.spider.yqgov.task; import javax.annotation.Resource; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; /** * @remark * @author luzh * @createTime 2017年7月5日 下午4:16:44 */ @Component public class ScheduleTask { @Resource private AsyncTask task; // 每个小时更新一次新闻列表 @Scheduled(cron = "0 0 * * * *") public void getColumnItems() { task.getColumnItems(); } @Scheduled(cron = "0 0/10 * * * *") public void crawlArticles () { task.crawlArticles(); } @Scheduled(cron = "0 0/10 * * * ?") public void pushToHomed() { task.pushToHomed(); } }
676
0.680685
0.647975
35
17.342857
16.071169
59
false
false
0
0
0
0
0
0
0.885714
false
false
13
62392ca27cf1d9e47172e38af97f32c3cfdc3294
9,663,676,446,052
56178d35c64914d9801779e296d78d7cbd7d4010
/Week4/src/filedemos/FileDemo.java
246f26ebaab5239584a82f3feafe14f8618d447e
[]
no_license
michael-maderich/PerScholas_MM
https://github.com/michael-maderich/PerScholas_MM
02707ef8865ab46a5d5de47a31c22d54bbaead4e
773b61c54c66b9575838439136b0aff402b822f5
refs/heads/main
2023-06-04T19:04:32.331000
2021-06-28T03:47:53
2021-06-28T03:47:53
352,759,962
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package filedemos; import java.io.File; public class FileDemo { public static void main(String[] args) { String fname = ""; } }
UTF-8
Java
151
java
FileDemo.java
Java
[]
null
[]
package filedemos; import java.io.File; public class FileDemo { public static void main(String[] args) { String fname = ""; } }
151
0.609272
0.609272
12
10.583333
12.906447
41
false
false
0
0
0
0
0
0
0.75
false
false
13
9852f70b2f5f241985e7915725720f77bce13d2a
28,656,021,839,376
dbb5088fceb044f0b50c6122cb1aeea17604c8da
/admin-web/src/main/java/org/jigang/plat/admin/web/controller/sys/SysLoginController.java
6bed68d5684b1fe3d6515cbf1f3db5a8bc2ca35f
[]
no_license
tihu0511/admin_plat
https://github.com/tihu0511/admin_plat
64027a8cf93152ee109deed6d2999885fe9a6b5e
801b6b314c8229012e729d28f7a8cc1a207d1084
refs/heads/master
2020-06-09T09:29:24.650000
2017-03-28T05:33:24
2017-03-28T05:33:24
76,045,520
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.jigang.plat.admin.web.controller.sys; import com.google.code.kaptcha.Constants; import com.google.code.kaptcha.Producer; import org.apache.shiro.authc.*; import org.apache.shiro.crypto.hash.Sha256Hash; import org.apache.shiro.subject.Subject; import org.jigang.plat.admin.util.ShiroUtil; import org.jigang.plat.admin.util.WebResponse; import org.jigang.plat.admin.web.controller.BaseController; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse; import java.awt.image.BufferedImage; import java.io.IOException; /** * 登录controller * * @author wjg * @date 2017/1/1. */ @Controller public class SysLoginController extends BaseController { @Autowired private Producer producer; @RequestMapping("captcha.jpg") public void captcha(HttpServletResponse response)throws ServletException, IOException { response.setHeader("Cache-Control", "no-store, no-cache"); response.setContentType("image/jpeg"); //生成文字验证码 String text = producer.createText(); //生成图片验证码 BufferedImage image = producer.createImage(text); //保存到shiro session ShiroUtil.setSessionAttribute(Constants.KAPTCHA_SESSION_KEY, text); ServletOutputStream out = response.getOutputStream(); ImageIO.write(image, "jpg", out); } /** * 登录 */ @ResponseBody @RequestMapping(value = "/sys/login", method = RequestMethod.POST) public WebResponse login(String username, String password, String captcha)throws IOException { String kaptcha = ShiroUtil.getKaptcha(Constants.KAPTCHA_SESSION_KEY); if(!captcha.equalsIgnoreCase(kaptcha)){ return WebResponse.error("验证码不正确"); } try{ Subject subject = ShiroUtil.getSubject(); //sha256加密 password = new Sha256Hash(password).toHex(); UsernamePasswordToken token = new UsernamePasswordToken(username, password); subject.login(token); }catch (UnknownAccountException e) { return WebResponse.error(e.getMessage()); }catch (IncorrectCredentialsException e) { return WebResponse.error(e.getMessage()); }catch (LockedAccountException e) { return WebResponse.error(e.getMessage()); }catch (AuthenticationException e) { return WebResponse.error("账户验证失败"); } return WebResponse.ok(); } /** * 退出 */ @RequestMapping(value = "logout", method = RequestMethod.GET) public String logout() { ShiroUtil.logout(); return "redirect:login.html"; } }
UTF-8
Java
3,089
java
SysLoginController.java
Java
[ { "context": "io.IOException;\n\n/**\n * 登录controller\n *\n * @author wjg\n * @date 2017/1/1.\n */\n@Controller\npublic class S", "end": 969, "score": 0.9996676445007324, "start": 966, "tag": "USERNAME", "value": "wjg" } ]
null
[]
package org.jigang.plat.admin.web.controller.sys; import com.google.code.kaptcha.Constants; import com.google.code.kaptcha.Producer; import org.apache.shiro.authc.*; import org.apache.shiro.crypto.hash.Sha256Hash; import org.apache.shiro.subject.Subject; import org.jigang.plat.admin.util.ShiroUtil; import org.jigang.plat.admin.util.WebResponse; import org.jigang.plat.admin.web.controller.BaseController; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse; import java.awt.image.BufferedImage; import java.io.IOException; /** * 登录controller * * @author wjg * @date 2017/1/1. */ @Controller public class SysLoginController extends BaseController { @Autowired private Producer producer; @RequestMapping("captcha.jpg") public void captcha(HttpServletResponse response)throws ServletException, IOException { response.setHeader("Cache-Control", "no-store, no-cache"); response.setContentType("image/jpeg"); //生成文字验证码 String text = producer.createText(); //生成图片验证码 BufferedImage image = producer.createImage(text); //保存到shiro session ShiroUtil.setSessionAttribute(Constants.KAPTCHA_SESSION_KEY, text); ServletOutputStream out = response.getOutputStream(); ImageIO.write(image, "jpg", out); } /** * 登录 */ @ResponseBody @RequestMapping(value = "/sys/login", method = RequestMethod.POST) public WebResponse login(String username, String password, String captcha)throws IOException { String kaptcha = ShiroUtil.getKaptcha(Constants.KAPTCHA_SESSION_KEY); if(!captcha.equalsIgnoreCase(kaptcha)){ return WebResponse.error("验证码不正确"); } try{ Subject subject = ShiroUtil.getSubject(); //sha256加密 password = new Sha256Hash(password).toHex(); UsernamePasswordToken token = new UsernamePasswordToken(username, password); subject.login(token); }catch (UnknownAccountException e) { return WebResponse.error(e.getMessage()); }catch (IncorrectCredentialsException e) { return WebResponse.error(e.getMessage()); }catch (LockedAccountException e) { return WebResponse.error(e.getMessage()); }catch (AuthenticationException e) { return WebResponse.error("账户验证失败"); } return WebResponse.ok(); } /** * 退出 */ @RequestMapping(value = "logout", method = RequestMethod.GET) public String logout() { ShiroUtil.logout(); return "redirect:login.html"; } }
3,089
0.698176
0.693201
89
32.876404
24.630674
98
false
false
0
0
0
0
0
0
0.58427
false
false
13
4150c3373fe226d7eafb2ad9dcd04e6c1e429d0e
3,204,045,628,609
699c582e835e38895fa8e82843c25c159dfa0292
/app/src/main/java/com/example/customview/CustomLayouManager/ActivityCustomLayoutManager.java
39f5cf6be605329b232fbf03f7e62eb0531a0f01
[]
no_license
Wubingyu/CustomView
https://github.com/Wubingyu/CustomView
d611256dfdd736e3bc08b7e4c296a43ef3240b29
ab82ec66e9ea7c67ad3f31666c1ecbb0db15f0ee
refs/heads/master
2020-05-18T04:25:50.368000
2019-05-29T13:45:45
2019-05-29T13:45:45
184,173,035
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.customview.CustomLayouManager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.RecyclerView; import com.example.customview.R; import java.util.ArrayList; public class ActivityCustomLayoutManager extends AppCompatActivity { ArrayList<RecyclerViewItem> items = new ArrayList<>(); RecyclerView recyclerView; RecyclerViewAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_custom_layout_manager); initItems(); adapter = new RecyclerViewAdapter(items); recyclerView = findViewById(R.id.ExploreFragment_RecyclerView); RecyclerView.LayoutManager layoutManager = new customLayoutManager(); recyclerView.setLayoutManager(layoutManager); recyclerView.setAdapter(adapter); } private void initItems() { RecyclerViewItem item1 = new RecyclerViewItem("how many roads must a man walk down"); RecyclerViewItem item2 = new RecyclerViewItem("The answer is blowing in the wind"); items.add(item1); items.add(item2); } }
UTF-8
Java
1,215
java
ActivityCustomLayoutManager.java
Java
[]
null
[]
package com.example.customview.CustomLayouManager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.RecyclerView; import com.example.customview.R; import java.util.ArrayList; public class ActivityCustomLayoutManager extends AppCompatActivity { ArrayList<RecyclerViewItem> items = new ArrayList<>(); RecyclerView recyclerView; RecyclerViewAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_custom_layout_manager); initItems(); adapter = new RecyclerViewAdapter(items); recyclerView = findViewById(R.id.ExploreFragment_RecyclerView); RecyclerView.LayoutManager layoutManager = new customLayoutManager(); recyclerView.setLayoutManager(layoutManager); recyclerView.setAdapter(adapter); } private void initItems() { RecyclerViewItem item1 = new RecyclerViewItem("how many roads must a man walk down"); RecyclerViewItem item2 = new RecyclerViewItem("The answer is blowing in the wind"); items.add(item1); items.add(item2); } }
1,215
0.734156
0.729218
37
31.837837
27.679159
93
false
false
0
0
0
0
0
0
0.567568
false
false
13
06a4dc46c43c78b4528a3c2412fa8e87af2dca88
18,159,121,743,260
2a50ae282ea828c6d8d12fe010739dbe5c6af698
/src/main/java/com/dairy/managment/app/entity/MilkEntryPrimaryKey.java
b2962b145db1728a3e8307b49b4997d475bbc71b
[]
no_license
ranjitnimbalkar/dairy-managment-app
https://github.com/ranjitnimbalkar/dairy-managment-app
12024d99ca4600347d1e003ffbde5dd84da36ffd
233dba790a783c15c89415243ec3beab82ec5753
refs/heads/main
2023-07-12T19:39:53.478000
2021-08-13T03:26:28
2021-08-13T03:26:28
395,507,707
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.dairy.managment.app.entity; import java.io.Serializable; import java.util.Date; import javax.persistence.Column; import javax.persistence.Convert; import javax.persistence.Temporal; import javax.persistence.TemporalType; import com.dairy.managment.app.enums.MilkTime; import com.dairy.managment.app.enums.MilkTimeConverter; import lombok.Data; @Data public class MilkEntryPrimaryKey implements Serializable{ private static final long serialVersionUID = 1L; public MilkEntryPrimaryKey() { super(); } @Column(name = "customer_id") private long customerId; @Temporal(TemporalType.DATE) private Date date; @Convert(converter = MilkTimeConverter.class) private MilkTime milk_time; }
UTF-8
Java
715
java
MilkEntryPrimaryKey.java
Java
[]
null
[]
package com.dairy.managment.app.entity; import java.io.Serializable; import java.util.Date; import javax.persistence.Column; import javax.persistence.Convert; import javax.persistence.Temporal; import javax.persistence.TemporalType; import com.dairy.managment.app.enums.MilkTime; import com.dairy.managment.app.enums.MilkTimeConverter; import lombok.Data; @Data public class MilkEntryPrimaryKey implements Serializable{ private static final long serialVersionUID = 1L; public MilkEntryPrimaryKey() { super(); } @Column(name = "customer_id") private long customerId; @Temporal(TemporalType.DATE) private Date date; @Convert(converter = MilkTimeConverter.class) private MilkTime milk_time; }
715
0.791608
0.79021
34
20.029411
18.622385
57
false
false
0
0
0
0
0
0
0.852941
false
false
13
ec3cde8a90c2aec63715e7224fa1de72330eff59
32,521,492,409,531
80117add94a71ce17881e6df7aaf3cae5372e9ec
/tcsystem/src/com/nuaa/ec/teach/baseSet/action/TermSetAction.java
61221afaf40d0293bd11df1d6942e2203c1bc549
[]
no_license
zxmals/TEST
https://github.com/zxmals/TEST
3ee9cbfab69f72171b777353c941eb8989726aa1
ddc7eaaf54102ec87287d3967bcbb1f63fc0e1fb
refs/heads/master
2020-04-12T08:09:55.932000
2017-03-05T08:30:57
2017-03-05T08:30:57
63,404,249
2
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.nuaa.ec.teach.baseSet.action; import java.io.IOException; import java.util.Map; import javax.servlet.http.HttpServletResponse; import org.apache.struts2.interceptor.RequestAware; import org.hibernate.Transaction; import com.nuaa.ec.dao.TftermDAO; import com.nuaa.ec.model.Tfterm; import com.nuaa.ec.utils.PrimaryKMaker; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; public class TermSetAction extends ActionSupport implements RequestAware{ private Tfterm term; private TftermDAO termDao = new TftermDAO(); private PrimaryKMaker pk = new PrimaryKMaker(); private Map<String, Object> request; private Integer operstatus; public String execute(){ return SUCCESS; } public String getTermList() throws Exception{ request.put("Term", termDao.findAll()); return "success"; } public String addTerm() throws Exception{ term.setTermId(pk.mkpk("termID", "Tfterm", "Term")); term.setSpareTire("1"); Transaction txTransaction = null; try { termDao.save(term); txTransaction = termDao.getSession().beginTransaction(); txTransaction.commit(); this.setOperstatus(1); getTermList(); } catch (Exception e) { // TODO: handle exception txTransaction.rollback(); this.setOperstatus(-1); throw e; }finally{ termDao.closeSession(); } return "success"; } public void updateTerm() throws Exception{ Transaction tx = null; term.setSpareTire("1"); HttpServletResponse resp = (HttpServletResponse) ActionContext.getContext().get(org.apache.struts2.StrutsStatics.HTTP_RESPONSE); try { termDao.merge(term); tx = termDao.getSession().beginTransaction(); tx.commit(); resp.getWriter().write("succ"); } catch (Exception e) { // TODO: handle exception tx.rollback(); try { resp.getWriter().write("fail"); } catch (IOException e1) { // TODO Auto-generated catch block throw e; } throw e; }finally{ termDao.closeSession(); } } public void deleteTerm() throws Exception{ Transaction tx = null; term.setSpareTire("0"); HttpServletResponse resp = (HttpServletResponse)ActionContext.getContext().get(org.apache.struts2.StrutsStatics.HTTP_RESPONSE); try { termDao.merge(term); tx = termDao.getSession().beginTransaction(); tx.commit(); resp.getWriter().write("succ"); } catch (Exception e) { // TODO: handle exception tx.rollback(); throw e; }finally{ termDao.closeSession(); } } public Tfterm getTerm() { return term; } public void setTerm(Tfterm term) { this.term = term; } public void setRequest(Map<String, Object> request) { // TODO Auto-generated method stub this.request = request; } public Integer getOperstatus() { return operstatus; } public void setOperstatus(Integer operstatus) { this.operstatus = operstatus; } public Map<String, Object> getRequest() { return request; } }
UTF-8
Java
2,925
java
TermSetAction.java
Java
[]
null
[]
package com.nuaa.ec.teach.baseSet.action; import java.io.IOException; import java.util.Map; import javax.servlet.http.HttpServletResponse; import org.apache.struts2.interceptor.RequestAware; import org.hibernate.Transaction; import com.nuaa.ec.dao.TftermDAO; import com.nuaa.ec.model.Tfterm; import com.nuaa.ec.utils.PrimaryKMaker; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; public class TermSetAction extends ActionSupport implements RequestAware{ private Tfterm term; private TftermDAO termDao = new TftermDAO(); private PrimaryKMaker pk = new PrimaryKMaker(); private Map<String, Object> request; private Integer operstatus; public String execute(){ return SUCCESS; } public String getTermList() throws Exception{ request.put("Term", termDao.findAll()); return "success"; } public String addTerm() throws Exception{ term.setTermId(pk.mkpk("termID", "Tfterm", "Term")); term.setSpareTire("1"); Transaction txTransaction = null; try { termDao.save(term); txTransaction = termDao.getSession().beginTransaction(); txTransaction.commit(); this.setOperstatus(1); getTermList(); } catch (Exception e) { // TODO: handle exception txTransaction.rollback(); this.setOperstatus(-1); throw e; }finally{ termDao.closeSession(); } return "success"; } public void updateTerm() throws Exception{ Transaction tx = null; term.setSpareTire("1"); HttpServletResponse resp = (HttpServletResponse) ActionContext.getContext().get(org.apache.struts2.StrutsStatics.HTTP_RESPONSE); try { termDao.merge(term); tx = termDao.getSession().beginTransaction(); tx.commit(); resp.getWriter().write("succ"); } catch (Exception e) { // TODO: handle exception tx.rollback(); try { resp.getWriter().write("fail"); } catch (IOException e1) { // TODO Auto-generated catch block throw e; } throw e; }finally{ termDao.closeSession(); } } public void deleteTerm() throws Exception{ Transaction tx = null; term.setSpareTire("0"); HttpServletResponse resp = (HttpServletResponse)ActionContext.getContext().get(org.apache.struts2.StrutsStatics.HTTP_RESPONSE); try { termDao.merge(term); tx = termDao.getSession().beginTransaction(); tx.commit(); resp.getWriter().write("succ"); } catch (Exception e) { // TODO: handle exception tx.rollback(); throw e; }finally{ termDao.closeSession(); } } public Tfterm getTerm() { return term; } public void setTerm(Tfterm term) { this.term = term; } public void setRequest(Map<String, Object> request) { // TODO Auto-generated method stub this.request = request; } public Integer getOperstatus() { return operstatus; } public void setOperstatus(Integer operstatus) { this.operstatus = operstatus; } public Map<String, Object> getRequest() { return request; } }
2,925
0.709744
0.705983
127
22.031496
21.666382
130
false
false
0
0
0
0
0
0
2.07874
false
false
13
23c52d3b12d04754cf340f213300d1ef61d97218
24,781,961,338,273
481adc8f5686985a7b9241055d50ff6084beea95
/appsearch/local-storage/src/main/java/androidx/appsearch/localstorage/converter/GenericDocumentToProtoConverter.java
c5980455612c5cc73aa0b83c077aba6efa813adf
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
RikkaW/androidx
https://github.com/RikkaW/androidx
5f5e8a996f950a85698073330c16f5341b48e516
6d53f95e5d979366cf7935ad7f4f14f76a951ea5
refs/heads/androidx-main
2023-06-18T22:35:12.976000
2021-07-24T13:53:34
2021-07-24T13:53:34
389,105,112
4
0
Apache-2.0
true
2021-07-24T13:53:34
2021-07-24T13:25:43
2021-07-24T13:25:45
2021-07-24T13:53:34
634,125
0
0
0
null
false
false
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.appsearch.localstorage.converter; import androidx.annotation.NonNull; import androidx.annotation.RestrictTo; import androidx.appsearch.app.GenericDocument; import androidx.core.util.Preconditions; import com.google.android.icing.proto.DocumentProto; import com.google.android.icing.proto.PropertyProto; import com.google.android.icing.protobuf.ByteString; import java.util.ArrayList; import java.util.Collections; /** * Translates a {@link GenericDocument} into a {@link DocumentProto}. * * @hide */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) public final class GenericDocumentToProtoConverter { private GenericDocumentToProtoConverter() {} /** Converts a {@link GenericDocument} into a {@link DocumentProto}. */ @NonNull @SuppressWarnings("unchecked") public static DocumentProto toDocumentProto(@NonNull GenericDocument document) { Preconditions.checkNotNull(document); DocumentProto.Builder mProtoBuilder = DocumentProto.newBuilder(); mProtoBuilder.setUri(document.getUri()) .setSchema(document.getSchemaType()) .setNamespace(document.getNamespace()) .setScore(document.getScore()) .setTtlMs(document.getTtlMillis()) .setCreationTimestampMs(document.getCreationTimestampMillis()); ArrayList<String> keys = new ArrayList<>(document.getPropertyNames()); Collections.sort(keys); for (int i = 0; i < keys.size(); i++) { String name = keys.get(i); PropertyProto.Builder propertyProto = PropertyProto.newBuilder().setName(name); Object property = document.getProperty(name); if (property instanceof String[]) { String[] stringValues = (String[]) property; for (int j = 0; j < stringValues.length; j++) { propertyProto.addStringValues(stringValues[j]); } } else if (property instanceof long[]) { long[] longValues = (long[]) property; for (int j = 0; j < longValues.length; j++) { propertyProto.addInt64Values(longValues[j]); } } else if (property instanceof double[]) { double[] doubleValues = (double[]) property; for (int j = 0; j < doubleValues.length; j++) { propertyProto.addDoubleValues(doubleValues[j]); } } else if (property instanceof boolean[]) { boolean[] booleanValues = (boolean[]) property; for (int j = 0; j < booleanValues.length; j++) { propertyProto.addBooleanValues(booleanValues[j]); } } else if (property instanceof byte[][]) { byte[][] bytesValues = (byte[][]) property; for (int j = 0; j < bytesValues.length; j++) { propertyProto.addBytesValues(ByteString.copyFrom(bytesValues[j])); } } else if (property instanceof GenericDocument[]) { GenericDocument[] documentValues = (GenericDocument[]) property; for (int j = 0; j < documentValues.length; j++) { DocumentProto proto = toDocumentProto(documentValues[j]); propertyProto.addDocumentValues(proto); } } else { throw new IllegalStateException( String.format("Property \"%s\" has unsupported value type %s", name, property.getClass().toString())); } mProtoBuilder.addProperties(propertyProto); } return mProtoBuilder.build(); } /** Converts a {@link DocumentProto} into a {@link GenericDocument}. */ @NonNull public static GenericDocument toGenericDocument(@NonNull DocumentProto proto) { Preconditions.checkNotNull(proto); GenericDocument.Builder<?> documentBuilder = new GenericDocument.Builder<>(proto.getUri(), proto.getSchema()) .setNamespace(proto.getNamespace()) .setScore(proto.getScore()) .setTtlMillis(proto.getTtlMs()) .setCreationTimestampMillis(proto.getCreationTimestampMs()); for (int i = 0; i < proto.getPropertiesCount(); i++) { PropertyProto property = proto.getProperties(i); String name = property.getName(); if (property.getStringValuesCount() > 0) { String[] values = new String[property.getStringValuesCount()]; for (int j = 0; j < values.length; j++) { values[j] = property.getStringValues(j); } documentBuilder.setPropertyString(name, values); } else if (property.getInt64ValuesCount() > 0) { long[] values = new long[property.getInt64ValuesCount()]; for (int j = 0; j < values.length; j++) { values[j] = property.getInt64Values(j); } documentBuilder.setPropertyLong(name, values); } else if (property.getDoubleValuesCount() > 0) { double[] values = new double[property.getDoubleValuesCount()]; for (int j = 0; j < values.length; j++) { values[j] = property.getDoubleValues(j); } documentBuilder.setPropertyDouble(name, values); } else if (property.getBooleanValuesCount() > 0) { boolean[] values = new boolean[property.getBooleanValuesCount()]; for (int j = 0; j < values.length; j++) { values[j] = property.getBooleanValues(j); } documentBuilder.setPropertyBoolean(name, values); } else if (property.getBytesValuesCount() > 0) { byte[][] values = new byte[property.getBytesValuesCount()][]; for (int j = 0; j < values.length; j++) { values[j] = property.getBytesValues(j).toByteArray(); } documentBuilder.setPropertyBytes(name, values); } else if (property.getDocumentValuesCount() > 0) { GenericDocument[] values = new GenericDocument[property.getDocumentValuesCount()]; for (int j = 0; j < values.length; j++) { values[j] = toGenericDocument(property.getDocumentValues(j)); } documentBuilder.setPropertyDocument(name, values); } else { throw new IllegalStateException("Unknown type of value: " + name); } } return documentBuilder.build(); } }
UTF-8
Java
7,408
java
GenericDocumentToProtoConverter.java
Java
[]
null
[]
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.appsearch.localstorage.converter; import androidx.annotation.NonNull; import androidx.annotation.RestrictTo; import androidx.appsearch.app.GenericDocument; import androidx.core.util.Preconditions; import com.google.android.icing.proto.DocumentProto; import com.google.android.icing.proto.PropertyProto; import com.google.android.icing.protobuf.ByteString; import java.util.ArrayList; import java.util.Collections; /** * Translates a {@link GenericDocument} into a {@link DocumentProto}. * * @hide */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) public final class GenericDocumentToProtoConverter { private GenericDocumentToProtoConverter() {} /** Converts a {@link GenericDocument} into a {@link DocumentProto}. */ @NonNull @SuppressWarnings("unchecked") public static DocumentProto toDocumentProto(@NonNull GenericDocument document) { Preconditions.checkNotNull(document); DocumentProto.Builder mProtoBuilder = DocumentProto.newBuilder(); mProtoBuilder.setUri(document.getUri()) .setSchema(document.getSchemaType()) .setNamespace(document.getNamespace()) .setScore(document.getScore()) .setTtlMs(document.getTtlMillis()) .setCreationTimestampMs(document.getCreationTimestampMillis()); ArrayList<String> keys = new ArrayList<>(document.getPropertyNames()); Collections.sort(keys); for (int i = 0; i < keys.size(); i++) { String name = keys.get(i); PropertyProto.Builder propertyProto = PropertyProto.newBuilder().setName(name); Object property = document.getProperty(name); if (property instanceof String[]) { String[] stringValues = (String[]) property; for (int j = 0; j < stringValues.length; j++) { propertyProto.addStringValues(stringValues[j]); } } else if (property instanceof long[]) { long[] longValues = (long[]) property; for (int j = 0; j < longValues.length; j++) { propertyProto.addInt64Values(longValues[j]); } } else if (property instanceof double[]) { double[] doubleValues = (double[]) property; for (int j = 0; j < doubleValues.length; j++) { propertyProto.addDoubleValues(doubleValues[j]); } } else if (property instanceof boolean[]) { boolean[] booleanValues = (boolean[]) property; for (int j = 0; j < booleanValues.length; j++) { propertyProto.addBooleanValues(booleanValues[j]); } } else if (property instanceof byte[][]) { byte[][] bytesValues = (byte[][]) property; for (int j = 0; j < bytesValues.length; j++) { propertyProto.addBytesValues(ByteString.copyFrom(bytesValues[j])); } } else if (property instanceof GenericDocument[]) { GenericDocument[] documentValues = (GenericDocument[]) property; for (int j = 0; j < documentValues.length; j++) { DocumentProto proto = toDocumentProto(documentValues[j]); propertyProto.addDocumentValues(proto); } } else { throw new IllegalStateException( String.format("Property \"%s\" has unsupported value type %s", name, property.getClass().toString())); } mProtoBuilder.addProperties(propertyProto); } return mProtoBuilder.build(); } /** Converts a {@link DocumentProto} into a {@link GenericDocument}. */ @NonNull public static GenericDocument toGenericDocument(@NonNull DocumentProto proto) { Preconditions.checkNotNull(proto); GenericDocument.Builder<?> documentBuilder = new GenericDocument.Builder<>(proto.getUri(), proto.getSchema()) .setNamespace(proto.getNamespace()) .setScore(proto.getScore()) .setTtlMillis(proto.getTtlMs()) .setCreationTimestampMillis(proto.getCreationTimestampMs()); for (int i = 0; i < proto.getPropertiesCount(); i++) { PropertyProto property = proto.getProperties(i); String name = property.getName(); if (property.getStringValuesCount() > 0) { String[] values = new String[property.getStringValuesCount()]; for (int j = 0; j < values.length; j++) { values[j] = property.getStringValues(j); } documentBuilder.setPropertyString(name, values); } else if (property.getInt64ValuesCount() > 0) { long[] values = new long[property.getInt64ValuesCount()]; for (int j = 0; j < values.length; j++) { values[j] = property.getInt64Values(j); } documentBuilder.setPropertyLong(name, values); } else if (property.getDoubleValuesCount() > 0) { double[] values = new double[property.getDoubleValuesCount()]; for (int j = 0; j < values.length; j++) { values[j] = property.getDoubleValues(j); } documentBuilder.setPropertyDouble(name, values); } else if (property.getBooleanValuesCount() > 0) { boolean[] values = new boolean[property.getBooleanValuesCount()]; for (int j = 0; j < values.length; j++) { values[j] = property.getBooleanValues(j); } documentBuilder.setPropertyBoolean(name, values); } else if (property.getBytesValuesCount() > 0) { byte[][] values = new byte[property.getBytesValuesCount()][]; for (int j = 0; j < values.length; j++) { values[j] = property.getBytesValues(j).toByteArray(); } documentBuilder.setPropertyBytes(name, values); } else if (property.getDocumentValuesCount() > 0) { GenericDocument[] values = new GenericDocument[property.getDocumentValuesCount()]; for (int j = 0; j < values.length; j++) { values[j] = toGenericDocument(property.getDocumentValues(j)); } documentBuilder.setPropertyDocument(name, values); } else { throw new IllegalStateException("Unknown type of value: " + name); } } return documentBuilder.build(); } }
7,408
0.587203
0.582343
155
46.793549
25.802149
98
false
false
0
0
0
0
0
0
0.645161
false
false
13
39c4247026ac7aaa9b2e45cfa705d235a78e6f2f
22,763,326,684,556
fe36ef71abf8c93d6791f90e124ec5f52b8cf1bb
/Examples/src/main/java/com/groupdocs/watermark/examples/advanced_usage/adding_watermarks/add_watermarks_to_pdf/PdfRemoveWatermark.java
ebf5989786fbe05af2ac494ec7dc393cd0056c54
[ "MIT" ]
permissive
groupdocs-watermark/GroupDocs.Watermark-for-Java
https://github.com/groupdocs-watermark/GroupDocs.Watermark-for-Java
bf20e22062d97557de7aa09338d561c35a3bb683
fed5e7f0ed1c05bfb0e3890bb03179d4dc2d90cc
refs/heads/master
2022-12-09T08:38:20.165000
2021-06-24T12:00:00
2021-06-24T12:00:00
119,377,660
7
3
MIT
false
2022-12-06T00:39:43
2018-01-29T12:08:16
2021-11-29T11:02:41
2022-12-06T00:39:41
12,317
5
3
1
null
false
false
package com.groupdocs.watermark.examples.advanced_usage.adding_watermarks.add_watermarks_to_pdf; import com.groupdocs.watermark.Watermarker; import com.groupdocs.watermark.contents.PdfContent; import com.groupdocs.watermark.examples.Constants; import com.groupdocs.watermark.options.PdfLoadOptions; import com.groupdocs.watermark.search.ImageDctHashSearchCriteria; import com.groupdocs.watermark.search.ImageSearchCriteria; import com.groupdocs.watermark.search.PossibleWatermarkCollection; import com.groupdocs.watermark.search.TextSearchCriteria; public class PdfRemoveWatermark { /** * This example shows how to remove watermarks from a particular page. */ public static void run() { PdfLoadOptions loadOptions = new PdfLoadOptions(); // Constants.InDocumentPdf is an absolute or relative path to your document. Ex: "C:\\Docs\\document.pdf" Watermarker watermarker = new Watermarker(Constants.InDocumentPdf, loadOptions); // Initialize search criteria ImageSearchCriteria imageSearchCriteria = new ImageDctHashSearchCriteria(Constants.LogoPng); TextSearchCriteria textSearchCriteria = new TextSearchCriteria("Company Name"); PdfContent pdfContent = watermarker.getContent(PdfContent.class); PossibleWatermarkCollection possibleWatermarks = pdfContent.getPages().get_Item(0).search(imageSearchCriteria.or(textSearchCriteria)); // Remove all found watermarks for (int i = possibleWatermarks.getCount() - 1; i >= 0; i--) { possibleWatermarks.removeAt(i); } watermarker.save(Constants.OutDocumentPdf); watermarker.close(); } }
UTF-8
Java
1,717
java
PdfRemoveWatermark.java
Java
[]
null
[]
package com.groupdocs.watermark.examples.advanced_usage.adding_watermarks.add_watermarks_to_pdf; import com.groupdocs.watermark.Watermarker; import com.groupdocs.watermark.contents.PdfContent; import com.groupdocs.watermark.examples.Constants; import com.groupdocs.watermark.options.PdfLoadOptions; import com.groupdocs.watermark.search.ImageDctHashSearchCriteria; import com.groupdocs.watermark.search.ImageSearchCriteria; import com.groupdocs.watermark.search.PossibleWatermarkCollection; import com.groupdocs.watermark.search.TextSearchCriteria; public class PdfRemoveWatermark { /** * This example shows how to remove watermarks from a particular page. */ public static void run() { PdfLoadOptions loadOptions = new PdfLoadOptions(); // Constants.InDocumentPdf is an absolute or relative path to your document. Ex: "C:\\Docs\\document.pdf" Watermarker watermarker = new Watermarker(Constants.InDocumentPdf, loadOptions); // Initialize search criteria ImageSearchCriteria imageSearchCriteria = new ImageDctHashSearchCriteria(Constants.LogoPng); TextSearchCriteria textSearchCriteria = new TextSearchCriteria("Company Name"); PdfContent pdfContent = watermarker.getContent(PdfContent.class); PossibleWatermarkCollection possibleWatermarks = pdfContent.getPages().get_Item(0).search(imageSearchCriteria.or(textSearchCriteria)); // Remove all found watermarks for (int i = possibleWatermarks.getCount() - 1; i >= 0; i--) { possibleWatermarks.removeAt(i); } watermarker.save(Constants.OutDocumentPdf); watermarker.close(); } }
1,717
0.736168
0.73442
38
43.184212
36.55267
142
false
false
0
0
0
0
0
0
0.552632
false
false
13
1c3c1d23057f2a01fa0919bee6d74fba05209917
22,763,326,683,984
ee71c6606887b2ae9505d0e3cc04e5f701b52bef
/rongyi-crm5/src/main/java/com/gcrm/action/crm/ListTargetListAction.java
6b9e331d58ce5abd3bfaec1e27452672ac98d4a1
[]
no_license
mythread/rongyi_source
https://github.com/mythread/rongyi_source
24a6823f6c0f48d140262144221d2fc231f5957e
3da4d20548bd2609e4720ed83eda53fa45b6515c
refs/heads/master
2020-04-05T23:40:28.747000
2015-04-17T09:04:50
2015-04-17T09:04:50
34,106,925
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Copyright (C) 2012 - 2013, Grass CRM Studio * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.gcrm.action.crm; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.InputStream; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import javax.servlet.http.HttpServletResponse; import org.apache.struts2.ServletActionContext; import org.supercsv.io.CsvListReader; import org.supercsv.io.CsvMapWriter; import org.supercsv.io.ICsvMapWriter; import org.supercsv.prefs.CsvPreference; import com.gcrm.action.system.ListUserAction; import com.gcrm.domain.Account; import com.gcrm.domain.Campaign; import com.gcrm.domain.Contact; import com.gcrm.domain.Lead; import com.gcrm.domain.Target; import com.gcrm.domain.TargetList; import com.gcrm.domain.User; import com.gcrm.exception.ServiceException; import com.gcrm.service.IBaseService; import com.gcrm.util.CommonUtil; import com.gcrm.util.Constant; import com.gcrm.util.security.UserUtil; import com.gcrm.vo.SearchCondition; import com.gcrm.vo.SearchResult; /** * Lists TargetList * */ public class ListTargetListAction extends BaseListAction { private static final long serialVersionUID = -2404576552417042445L; private IBaseService<TargetList> baseService; private IBaseService<User> userService; private IBaseService<Campaign> campaignService; private TargetList targetList; private static final String CLAZZ = TargetList.class.getSimpleName(); /** * Gets the list data. * * @return null */ @Override public String list() throws Exception { SearchCondition searchCondition = getSearchCondition(); SearchResult<TargetList> result = baseService.getPaginationObjects( CLAZZ, searchCondition); Iterator<TargetList> targetLists = result.getResult().iterator(); long totalRecords = result.getTotalRecords(); getListJson(targetLists, totalRecords, null, false); return null; } /** * Gets the list data. * * @return null */ public String listFull() throws Exception { UserUtil.permissionCheck("view_targetList"); Map<String, String> fieldTypeMap = new HashMap<String, String>(); fieldTypeMap.put("created_on", Constant.DATA_TYPE_DATETIME); fieldTypeMap.put("updated_on", Constant.DATA_TYPE_DATETIME); User loginUser = UserUtil.getLoginUser(); SearchCondition searchCondition = getSearchCondition(fieldTypeMap, loginUser.getScope_targetList(), loginUser); SearchResult<TargetList> result = baseService.getPaginationObjects( CLAZZ, searchCondition); Iterator<TargetList> targetLists = result.getResult().iterator(); long totalRecords = result.getTotalRecords(); getListJson(targetLists, totalRecords, searchCondition, true); return null; } /** * Gets the list JSON data. * * @return list JSON data */ public static void getListJson(Iterator<TargetList> targetLists, long totalRecords, SearchCondition searchCondition, boolean isList) throws Exception { StringBuilder jsonBuilder = new StringBuilder(""); jsonBuilder .append(getJsonHeader(totalRecords, searchCondition, isList)); String assignedTo = null; while (targetLists.hasNext()) { TargetList instance = targetLists.next(); int id = instance.getId(); String name = CommonUtil.fromNullToEmpty(instance.getName()); User user = instance.getAssigned_to(); if (user != null) { assignedTo = user.getName(); } else { assignedTo = ""; } if (isList) { User createdBy = instance.getCreated_by(); String createdByName = ""; if (createdBy != null) { createdByName = CommonUtil.fromNullToEmpty(createdBy .getName()); } User updatedBy = instance.getUpdated_by(); String updatedByName = ""; if (updatedBy != null) { updatedByName = CommonUtil.fromNullToEmpty(updatedBy .getName()); } SimpleDateFormat dateFormat = new SimpleDateFormat( Constant.DATE_TIME_FORMAT); Date createdOn = instance.getCreated_on(); String createdOnName = ""; if (createdOn != null) { createdOnName = dateFormat.format(createdOn); } Date updatedOn = instance.getUpdated_on(); String updatedOnName = ""; if (updatedOn != null) { updatedOnName = dateFormat.format(updatedOn); } jsonBuilder.append("{\"cell\":[\"").append(id).append("\",\"") .append(name).append("\",\"").append(assignedTo) .append("\",\"").append(createdByName).append("\",\"") .append(updatedByName).append("\",\"") .append(createdOnName).append("\",\"") .append(updatedOnName).append("\"]}"); } else { jsonBuilder.append("{\"id\":\"").append(id) .append("\",\"name\":\"").append(name) .append("\",\"assigned_to.name\":\"") .append(assignedTo).append("\"}"); } if (targetLists.hasNext()) { jsonBuilder.append(","); } } jsonBuilder.append("]}"); // Returns JSON data back to page HttpServletResponse response = ServletActionContext.getResponse(); response.setContentType("text/html;charset=UTF-8"); response.getWriter().write(jsonBuilder.toString()); } /** * Gets the related accounts. * * @return null */ public String relateTargetListAccount() throws Exception { targetList = baseService.getEntityById(TargetList.class, id); Set<Account> accounts = targetList.getAccounts(); Iterator<Account> accountIterator = accounts.iterator(); long totalRecords = accounts.size(); ListAccountAction.getListJson(accountIterator, totalRecords, null, false); return null; } /** * Gets the related leads. * * @return null */ public String relateTargetListLead() throws Exception { targetList = baseService.getEntityById(TargetList.class, id); Set<Lead> leads = targetList.getLeads(); Iterator<Lead> leadIterator = leads.iterator(); long totalRecords = leads.size(); ListLeadAction.getListJson(leadIterator, totalRecords, null, false); return null; } public String relateTargetListContact() throws Exception { targetList = baseService.getEntityById(TargetList.class, id); Set<Contact> contacts = targetList.getContacts(); Iterator<Contact> contactIterator = contacts.iterator(); long totalRecords = contacts.size(); ListContactAction.getListJson(contactIterator, totalRecords, null, false); return null; } public String relateTargetListTarget() throws Exception { targetList = baseService.getEntityById(TargetList.class, id); Set<Target> targets = targetList.getTargets(); Iterator<Target> targetIterator = targets.iterator(); long totalRecords = targets.size(); ListTargetAction.getListJson(targetIterator, totalRecords, null, false); return null; } public String relateTargetListUser() throws Exception { targetList = baseService.getEntityById(TargetList.class, id); Set<User> users = targetList.getUsers(); Iterator<User> userIterator = users.iterator(); int totalRecords = users.size(); ListUserAction.getListJson(userIterator, totalRecords, null, false); return null; } /** * Selects the entities * * @return the SUCCESS result */ public String select() throws ServiceException { Campaign campaign = null; Set<TargetList> targetLists = null; if ("Campaign".equals(this.getRelationKey())) { campaign = campaignService.getEntityById(Campaign.class, Integer.valueOf(this.getRelationValue())); targetLists = campaign.getTargetLists(); } if (this.getSeleteIDs() != null) { String[] ids = seleteIDs.split(","); for (int i = 0; i < ids.length; i++) { String selectId = ids[i]; targetList = baseService.getEntityById(TargetList.class, Integer.valueOf(selectId)); targetLists.add(targetList); } } if ("Campaign".equals(this.getRelationKey())) { campaignService.makePersistent(campaign); } return SUCCESS; } /** * Unselects the entities * * @return the SUCCESS result */ public String unselect() throws ServiceException { Campaign campaign = null; Set<TargetList> targetLists = null; if ("Campaign".equals(this.getRelationKey())) { campaign = campaignService.getEntityById(Campaign.class, Integer.valueOf(this.getRelationValue())); targetLists = campaign.getTargetLists(); } if (this.getSeleteIDs() != null) { String[] ids = seleteIDs.split(","); Collection<TargetList> selectedTargetLists = new ArrayList<TargetList>(); for (int i = 0; i < ids.length; i++) { Integer selectId = Integer.valueOf(ids[i]); A: for (TargetList targetList : targetLists) { if (targetList.getId().intValue() == selectId.intValue()) { selectedTargetLists.add(targetList); break A; } } } targetLists.removeAll(selectedTargetLists); } if ("Campaign".equals(this.getRelationKey())) { campaignService.makePersistent(campaign); } return SUCCESS; } /** * Deletes the selected entities. * * @return the SUCCESS result */ public String delete() throws Exception { UserUtil.permissionCheck("delete_targetList"); baseService.batchDeleteEntity(TargetList.class, this.getSeleteIDs()); return SUCCESS; } /** * Copies the selected entities * * @return the SUCCESS result */ public String copy() throws Exception { UserUtil.permissionCheck("create_targetList"); if (this.getSeleteIDs() != null) { String[] ids = seleteIDs.split(","); for (int i = 0; i < ids.length; i++) { String copyid = ids[i]; TargetList oriRecord = baseService.getEntityById( TargetList.class, Integer.valueOf(copyid)); TargetList targetListRecord = oriRecord.clone(); targetListRecord.setId(null); this.getbaseService().makePersistent(targetListRecord); } } return SUCCESS; } /** * Exports the entities * * @return the exported entities inputStream */ public InputStream getInputStream() throws Exception { return getDownloadContent(false); } /** * Exports the template * * @return the exported template inputStream */ public InputStream getTemplateStream() throws Exception { return getDownloadContent(true); } private InputStream getDownloadContent(boolean isTemplate) throws Exception { UserUtil.permissionCheck("view_targetList"); String fileName = getText("entity.targetList.label") + ".csv"; fileName = new String(fileName.getBytes(), "ISO8859-1"); File file = new File(fileName); ICsvMapWriter writer = new CsvMapWriter(new FileWriter(file), CsvPreference.EXCEL_PREFERENCE); try { final String[] header = new String[] { getText("entity.id.label"), getText("entity.name.label"), getText("entity.notes.label"), getText("entity.assigned_to_id.label"), getText("entity.assigned_to_name.label") }; writer.writeHeader(header); if (!isTemplate) { String[] ids = seleteIDs.split(","); for (int i = 0; i < ids.length; i++) { String id = ids[i]; TargetList targetList = baseService.getEntityById( TargetList.class, Integer.parseInt(id)); final HashMap<String, ? super Object> data1 = new HashMap<String, Object>(); data1.put(header[0], targetList.getId()); data1.put(header[1], CommonUtil.fromNullToEmpty(targetList.getName())); data1.put(header[2], CommonUtil.fromNullToEmpty(targetList.getNotes())); if (targetList.getAssigned_to() != null) { data1.put(header[3], targetList.getAssigned_to() .getId()); data1.put(header[4], targetList.getAssigned_to() .getName()); } else { data1.put(header[3], ""); data1.put(header[4], ""); } writer.write(data1, header); } } } catch (Exception e) { throw e; } finally { writer.close(); } InputStream in = new FileInputStream(file); this.setFileName(fileName); return in; } /** * Imports the entities * * @return the SUCCESS result */ public String importCSV() throws Exception { File file = this.getUpload(); CsvListReader reader = new CsvListReader(new FileReader(file), CsvPreference.EXCEL_PREFERENCE); int failedNum = 0; int successfulNum = 0; try { final String[] header = reader.getCSVHeader(true); List<String> line = new ArrayList<String>(); Map<String, String> failedMsg = new HashMap<String, String>(); while ((line = reader.read()) != null) { Map<String, String> row = new HashMap<String, String>(); for (int i = 0; i < line.size(); i++) { row.put(header[i], line.get(i)); } TargetList targetList = new TargetList(); try { String id = row.get(getText("entity.id.label")); if (!CommonUtil.isNullOrEmpty(id)) { targetList.setId(Integer.parseInt(id)); } targetList.setName(CommonUtil.fromNullToEmpty(row .get(getText("entity.name.label")))); targetList.setNotes(CommonUtil.fromNullToEmpty(row .get(getText("entity.notes.label")))); String assignedToID = row .get(getText("entity.assigned_to_id.label")); if (CommonUtil.isNullOrEmpty(assignedToID)) { targetList.setAssigned_to(null); } else { User assignedTo = userService.getEntityById(User.class, Integer.parseInt(assignedToID)); targetList.setAssigned_to(assignedTo); } baseService.makePersistent(targetList); successfulNum++; } catch (Exception e) { failedNum++; String Name = CommonUtil.fromNullToEmpty(targetList .getName()); failedMsg.put(Name, e.getMessage()); } } this.setFailedMsg(failedMsg); this.setFailedNum(failedNum); this.setSuccessfulNum(successfulNum); this.setTotalNum(successfulNum + failedNum); } finally { reader.close(); } return SUCCESS; } @Override public String execute() throws Exception { return SUCCESS; } @Override protected String getEntityName() { return TargetList.class.getSimpleName(); } public IBaseService<TargetList> getbaseService() { return baseService; } public void setbaseService(IBaseService<TargetList> baseService) { this.baseService = baseService; } public TargetList getTargetList() { return targetList; } public void setTargetList(TargetList targetList) { this.targetList = targetList; } /** * @return the id */ @Override public Integer getId() { return id; } /** * @param id * the id to set */ @Override public void setId(Integer id) { this.id = id; } /** * @return the userService */ public IBaseService<User> getUserService() { return userService; } /** * @param userService * the userService to set */ public void setUserService(IBaseService<User> userService) { this.userService = userService; } /** * @return the campaignService */ public IBaseService<Campaign> getCampaignService() { return campaignService; } /** * @param campaignService * the campaignService to set */ public void setCampaignService(IBaseService<Campaign> campaignService) { this.campaignService = campaignService; } }
UTF-8
Java
19,006
java
ListTargetListAction.java
Java
[]
null
[]
/** * Copyright (C) 2012 - 2013, Grass CRM Studio * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.gcrm.action.crm; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.InputStream; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import javax.servlet.http.HttpServletResponse; import org.apache.struts2.ServletActionContext; import org.supercsv.io.CsvListReader; import org.supercsv.io.CsvMapWriter; import org.supercsv.io.ICsvMapWriter; import org.supercsv.prefs.CsvPreference; import com.gcrm.action.system.ListUserAction; import com.gcrm.domain.Account; import com.gcrm.domain.Campaign; import com.gcrm.domain.Contact; import com.gcrm.domain.Lead; import com.gcrm.domain.Target; import com.gcrm.domain.TargetList; import com.gcrm.domain.User; import com.gcrm.exception.ServiceException; import com.gcrm.service.IBaseService; import com.gcrm.util.CommonUtil; import com.gcrm.util.Constant; import com.gcrm.util.security.UserUtil; import com.gcrm.vo.SearchCondition; import com.gcrm.vo.SearchResult; /** * Lists TargetList * */ public class ListTargetListAction extends BaseListAction { private static final long serialVersionUID = -2404576552417042445L; private IBaseService<TargetList> baseService; private IBaseService<User> userService; private IBaseService<Campaign> campaignService; private TargetList targetList; private static final String CLAZZ = TargetList.class.getSimpleName(); /** * Gets the list data. * * @return null */ @Override public String list() throws Exception { SearchCondition searchCondition = getSearchCondition(); SearchResult<TargetList> result = baseService.getPaginationObjects( CLAZZ, searchCondition); Iterator<TargetList> targetLists = result.getResult().iterator(); long totalRecords = result.getTotalRecords(); getListJson(targetLists, totalRecords, null, false); return null; } /** * Gets the list data. * * @return null */ public String listFull() throws Exception { UserUtil.permissionCheck("view_targetList"); Map<String, String> fieldTypeMap = new HashMap<String, String>(); fieldTypeMap.put("created_on", Constant.DATA_TYPE_DATETIME); fieldTypeMap.put("updated_on", Constant.DATA_TYPE_DATETIME); User loginUser = UserUtil.getLoginUser(); SearchCondition searchCondition = getSearchCondition(fieldTypeMap, loginUser.getScope_targetList(), loginUser); SearchResult<TargetList> result = baseService.getPaginationObjects( CLAZZ, searchCondition); Iterator<TargetList> targetLists = result.getResult().iterator(); long totalRecords = result.getTotalRecords(); getListJson(targetLists, totalRecords, searchCondition, true); return null; } /** * Gets the list JSON data. * * @return list JSON data */ public static void getListJson(Iterator<TargetList> targetLists, long totalRecords, SearchCondition searchCondition, boolean isList) throws Exception { StringBuilder jsonBuilder = new StringBuilder(""); jsonBuilder .append(getJsonHeader(totalRecords, searchCondition, isList)); String assignedTo = null; while (targetLists.hasNext()) { TargetList instance = targetLists.next(); int id = instance.getId(); String name = CommonUtil.fromNullToEmpty(instance.getName()); User user = instance.getAssigned_to(); if (user != null) { assignedTo = user.getName(); } else { assignedTo = ""; } if (isList) { User createdBy = instance.getCreated_by(); String createdByName = ""; if (createdBy != null) { createdByName = CommonUtil.fromNullToEmpty(createdBy .getName()); } User updatedBy = instance.getUpdated_by(); String updatedByName = ""; if (updatedBy != null) { updatedByName = CommonUtil.fromNullToEmpty(updatedBy .getName()); } SimpleDateFormat dateFormat = new SimpleDateFormat( Constant.DATE_TIME_FORMAT); Date createdOn = instance.getCreated_on(); String createdOnName = ""; if (createdOn != null) { createdOnName = dateFormat.format(createdOn); } Date updatedOn = instance.getUpdated_on(); String updatedOnName = ""; if (updatedOn != null) { updatedOnName = dateFormat.format(updatedOn); } jsonBuilder.append("{\"cell\":[\"").append(id).append("\",\"") .append(name).append("\",\"").append(assignedTo) .append("\",\"").append(createdByName).append("\",\"") .append(updatedByName).append("\",\"") .append(createdOnName).append("\",\"") .append(updatedOnName).append("\"]}"); } else { jsonBuilder.append("{\"id\":\"").append(id) .append("\",\"name\":\"").append(name) .append("\",\"assigned_to.name\":\"") .append(assignedTo).append("\"}"); } if (targetLists.hasNext()) { jsonBuilder.append(","); } } jsonBuilder.append("]}"); // Returns JSON data back to page HttpServletResponse response = ServletActionContext.getResponse(); response.setContentType("text/html;charset=UTF-8"); response.getWriter().write(jsonBuilder.toString()); } /** * Gets the related accounts. * * @return null */ public String relateTargetListAccount() throws Exception { targetList = baseService.getEntityById(TargetList.class, id); Set<Account> accounts = targetList.getAccounts(); Iterator<Account> accountIterator = accounts.iterator(); long totalRecords = accounts.size(); ListAccountAction.getListJson(accountIterator, totalRecords, null, false); return null; } /** * Gets the related leads. * * @return null */ public String relateTargetListLead() throws Exception { targetList = baseService.getEntityById(TargetList.class, id); Set<Lead> leads = targetList.getLeads(); Iterator<Lead> leadIterator = leads.iterator(); long totalRecords = leads.size(); ListLeadAction.getListJson(leadIterator, totalRecords, null, false); return null; } public String relateTargetListContact() throws Exception { targetList = baseService.getEntityById(TargetList.class, id); Set<Contact> contacts = targetList.getContacts(); Iterator<Contact> contactIterator = contacts.iterator(); long totalRecords = contacts.size(); ListContactAction.getListJson(contactIterator, totalRecords, null, false); return null; } public String relateTargetListTarget() throws Exception { targetList = baseService.getEntityById(TargetList.class, id); Set<Target> targets = targetList.getTargets(); Iterator<Target> targetIterator = targets.iterator(); long totalRecords = targets.size(); ListTargetAction.getListJson(targetIterator, totalRecords, null, false); return null; } public String relateTargetListUser() throws Exception { targetList = baseService.getEntityById(TargetList.class, id); Set<User> users = targetList.getUsers(); Iterator<User> userIterator = users.iterator(); int totalRecords = users.size(); ListUserAction.getListJson(userIterator, totalRecords, null, false); return null; } /** * Selects the entities * * @return the SUCCESS result */ public String select() throws ServiceException { Campaign campaign = null; Set<TargetList> targetLists = null; if ("Campaign".equals(this.getRelationKey())) { campaign = campaignService.getEntityById(Campaign.class, Integer.valueOf(this.getRelationValue())); targetLists = campaign.getTargetLists(); } if (this.getSeleteIDs() != null) { String[] ids = seleteIDs.split(","); for (int i = 0; i < ids.length; i++) { String selectId = ids[i]; targetList = baseService.getEntityById(TargetList.class, Integer.valueOf(selectId)); targetLists.add(targetList); } } if ("Campaign".equals(this.getRelationKey())) { campaignService.makePersistent(campaign); } return SUCCESS; } /** * Unselects the entities * * @return the SUCCESS result */ public String unselect() throws ServiceException { Campaign campaign = null; Set<TargetList> targetLists = null; if ("Campaign".equals(this.getRelationKey())) { campaign = campaignService.getEntityById(Campaign.class, Integer.valueOf(this.getRelationValue())); targetLists = campaign.getTargetLists(); } if (this.getSeleteIDs() != null) { String[] ids = seleteIDs.split(","); Collection<TargetList> selectedTargetLists = new ArrayList<TargetList>(); for (int i = 0; i < ids.length; i++) { Integer selectId = Integer.valueOf(ids[i]); A: for (TargetList targetList : targetLists) { if (targetList.getId().intValue() == selectId.intValue()) { selectedTargetLists.add(targetList); break A; } } } targetLists.removeAll(selectedTargetLists); } if ("Campaign".equals(this.getRelationKey())) { campaignService.makePersistent(campaign); } return SUCCESS; } /** * Deletes the selected entities. * * @return the SUCCESS result */ public String delete() throws Exception { UserUtil.permissionCheck("delete_targetList"); baseService.batchDeleteEntity(TargetList.class, this.getSeleteIDs()); return SUCCESS; } /** * Copies the selected entities * * @return the SUCCESS result */ public String copy() throws Exception { UserUtil.permissionCheck("create_targetList"); if (this.getSeleteIDs() != null) { String[] ids = seleteIDs.split(","); for (int i = 0; i < ids.length; i++) { String copyid = ids[i]; TargetList oriRecord = baseService.getEntityById( TargetList.class, Integer.valueOf(copyid)); TargetList targetListRecord = oriRecord.clone(); targetListRecord.setId(null); this.getbaseService().makePersistent(targetListRecord); } } return SUCCESS; } /** * Exports the entities * * @return the exported entities inputStream */ public InputStream getInputStream() throws Exception { return getDownloadContent(false); } /** * Exports the template * * @return the exported template inputStream */ public InputStream getTemplateStream() throws Exception { return getDownloadContent(true); } private InputStream getDownloadContent(boolean isTemplate) throws Exception { UserUtil.permissionCheck("view_targetList"); String fileName = getText("entity.targetList.label") + ".csv"; fileName = new String(fileName.getBytes(), "ISO8859-1"); File file = new File(fileName); ICsvMapWriter writer = new CsvMapWriter(new FileWriter(file), CsvPreference.EXCEL_PREFERENCE); try { final String[] header = new String[] { getText("entity.id.label"), getText("entity.name.label"), getText("entity.notes.label"), getText("entity.assigned_to_id.label"), getText("entity.assigned_to_name.label") }; writer.writeHeader(header); if (!isTemplate) { String[] ids = seleteIDs.split(","); for (int i = 0; i < ids.length; i++) { String id = ids[i]; TargetList targetList = baseService.getEntityById( TargetList.class, Integer.parseInt(id)); final HashMap<String, ? super Object> data1 = new HashMap<String, Object>(); data1.put(header[0], targetList.getId()); data1.put(header[1], CommonUtil.fromNullToEmpty(targetList.getName())); data1.put(header[2], CommonUtil.fromNullToEmpty(targetList.getNotes())); if (targetList.getAssigned_to() != null) { data1.put(header[3], targetList.getAssigned_to() .getId()); data1.put(header[4], targetList.getAssigned_to() .getName()); } else { data1.put(header[3], ""); data1.put(header[4], ""); } writer.write(data1, header); } } } catch (Exception e) { throw e; } finally { writer.close(); } InputStream in = new FileInputStream(file); this.setFileName(fileName); return in; } /** * Imports the entities * * @return the SUCCESS result */ public String importCSV() throws Exception { File file = this.getUpload(); CsvListReader reader = new CsvListReader(new FileReader(file), CsvPreference.EXCEL_PREFERENCE); int failedNum = 0; int successfulNum = 0; try { final String[] header = reader.getCSVHeader(true); List<String> line = new ArrayList<String>(); Map<String, String> failedMsg = new HashMap<String, String>(); while ((line = reader.read()) != null) { Map<String, String> row = new HashMap<String, String>(); for (int i = 0; i < line.size(); i++) { row.put(header[i], line.get(i)); } TargetList targetList = new TargetList(); try { String id = row.get(getText("entity.id.label")); if (!CommonUtil.isNullOrEmpty(id)) { targetList.setId(Integer.parseInt(id)); } targetList.setName(CommonUtil.fromNullToEmpty(row .get(getText("entity.name.label")))); targetList.setNotes(CommonUtil.fromNullToEmpty(row .get(getText("entity.notes.label")))); String assignedToID = row .get(getText("entity.assigned_to_id.label")); if (CommonUtil.isNullOrEmpty(assignedToID)) { targetList.setAssigned_to(null); } else { User assignedTo = userService.getEntityById(User.class, Integer.parseInt(assignedToID)); targetList.setAssigned_to(assignedTo); } baseService.makePersistent(targetList); successfulNum++; } catch (Exception e) { failedNum++; String Name = CommonUtil.fromNullToEmpty(targetList .getName()); failedMsg.put(Name, e.getMessage()); } } this.setFailedMsg(failedMsg); this.setFailedNum(failedNum); this.setSuccessfulNum(successfulNum); this.setTotalNum(successfulNum + failedNum); } finally { reader.close(); } return SUCCESS; } @Override public String execute() throws Exception { return SUCCESS; } @Override protected String getEntityName() { return TargetList.class.getSimpleName(); } public IBaseService<TargetList> getbaseService() { return baseService; } public void setbaseService(IBaseService<TargetList> baseService) { this.baseService = baseService; } public TargetList getTargetList() { return targetList; } public void setTargetList(TargetList targetList) { this.targetList = targetList; } /** * @return the id */ @Override public Integer getId() { return id; } /** * @param id * the id to set */ @Override public void setId(Integer id) { this.id = id; } /** * @return the userService */ public IBaseService<User> getUserService() { return userService; } /** * @param userService * the userService to set */ public void setUserService(IBaseService<User> userService) { this.userService = userService; } /** * @return the campaignService */ public IBaseService<Campaign> getCampaignService() { return campaignService; } /** * @param campaignService * the campaignService to set */ public void setCampaignService(IBaseService<Campaign> campaignService) { this.campaignService = campaignService; } }
19,006
0.573082
0.569873
545
33.873394
24.4548
96
false
false
0
0
0
0
0
0
0.581651
false
false
13
98c17948bd796938d8652d08799f02cae0051856
22,763,326,686,341
94d82f16916586350f5ab329718d515e95684076
/src/test/java/at/porscheinformatik/tapestry/csrfprotection/tests/off/services/OffModeModule.java
30011baa516f81f13343440233ae8c0f8c8473ae
[ "Apache-2.0" ]
permissive
porscheinformatik/tapestry-csrf-protection
https://github.com/porscheinformatik/tapestry-csrf-protection
a1f67a35017d2de0df7ff68d05a82034e46124bc
6924d1176d14bf4866e8557b9dc8e963b3c42b61
refs/heads/master
2023-04-27T20:59:22.007000
2021-09-08T19:37:58
2021-09-08T19:37:58
13,292,002
8
9
Apache-2.0
false
2023-04-18T18:13:54
2013-10-03T06:31:05
2021-09-08T19:41:27
2023-04-18T18:13:54
153
9
9
11
Java
false
false
package at.porscheinformatik.tapestry.csrfprotection.tests.off.services; import org.apache.tapestry5.SymbolConstants; import at.porscheinformatik.tapestry.csrfprotection.CsrfConstants; import at.porscheinformatik.tapestry.csrfprotection.CsrfProtectionMode; import org.apache.tapestry5.commons.MappedConfiguration; import org.apache.tapestry5.ioc.ServiceBinder; public class OffModeModule { public static void bind(ServiceBinder binder) { } public static void contributeApplicationDefaults(MappedConfiguration<String, String> configuration) { configuration.add(SymbolConstants.SUPPORTED_LOCALES, "en"); configuration.add(SymbolConstants.PRODUCTION_MODE, "false"); configuration.add(SymbolConstants.APPLICATION_VERSION, "1.0-SNAPSHOT"); configuration.add(CsrfConstants.CSRF_PROTECTION_MODE, CsrfProtectionMode.OFF.name()); } }
UTF-8
Java
884
java
OffModeModule.java
Java
[]
null
[]
package at.porscheinformatik.tapestry.csrfprotection.tests.off.services; import org.apache.tapestry5.SymbolConstants; import at.porscheinformatik.tapestry.csrfprotection.CsrfConstants; import at.porscheinformatik.tapestry.csrfprotection.CsrfProtectionMode; import org.apache.tapestry5.commons.MappedConfiguration; import org.apache.tapestry5.ioc.ServiceBinder; public class OffModeModule { public static void bind(ServiceBinder binder) { } public static void contributeApplicationDefaults(MappedConfiguration<String, String> configuration) { configuration.add(SymbolConstants.SUPPORTED_LOCALES, "en"); configuration.add(SymbolConstants.PRODUCTION_MODE, "false"); configuration.add(SymbolConstants.APPLICATION_VERSION, "1.0-SNAPSHOT"); configuration.add(CsrfConstants.CSRF_PROTECTION_MODE, CsrfProtectionMode.OFF.name()); } }
884
0.791855
0.786199
22
39.18182
34.235329
103
false
false
0
0
0
0
0
0
0.681818
false
false
13
7d42265fc3346738f084d2660f4b8d66ceb132fe
13,752,485,314,848
241bbcc2827a2d4bd8715aaed52a81fe64a997f1
/httplibs/src/main/java/com/srtianxia/httplibs/Response.java
fb816e79264b780b53f019ea135bcc713332ad4e
[]
no_license
srtianxia/AnnotationHttp
https://github.com/srtianxia/AnnotationHttp
28046f97634346b84e363dc2d61858770deee059
657bf21804100f4c22e4de7762499bc5356c287f
refs/heads/master
2021-01-12T14:06:47.967000
2016-10-10T09:35:12
2016-10-10T09:35:12
70,160,365
7
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.srtianxia.httplibs; /** * Created by srtianxia on 2016/10/3. */ public class Response { private String response; public Response(String response) { this.response = response; } public String string() { return response; } }
UTF-8
Java
276
java
Response.java
Java
[ { "context": "package com.srtianxia.httplibs;\n\n/**\n * Created by srtianxia on 2016/10/3.\n */\n\npublic class Response {\n pr", "end": 60, "score": 0.9995891451835632, "start": 51, "tag": "USERNAME", "value": "srtianxia" } ]
null
[]
package com.srtianxia.httplibs; /** * Created by srtianxia on 2016/10/3. */ public class Response { private String response; public Response(String response) { this.response = response; } public String string() { return response; } }
276
0.630435
0.605072
17
15.235294
14.671018
38
false
false
0
0
0
0
0
0
0.235294
false
false
13
4afd18ed1ee2aa0abb803f2fa8ed4ef52c046f6f
9,646,496,596,346
db2d61ccf1646da9a6ab12362acad59cc2a5ae2b
/src/test/Test.java
7d52ab7303392284a48dd71c3332776da2e3f196
[]
no_license
lyupan/sxjd-v2
https://github.com/lyupan/sxjd-v2
e0ae5a994820621d80ed32ebfa3a3145311ea553
8bee342e0ae69704c5d10ee5bf78f88470bb5f1d
refs/heads/master
2021-01-19T20:49:38.593000
2017-04-18T00:50:39
2017-04-18T00:50:39
88,564,339
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package test; import io.jsonwebtoken.JwtBuilder; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import java.security.Key; import java.util.Date; import io.jsonwebtoken.Claims; import javax.crypto.spec.SecretKeySpec; import javax.xml.bind.DatatypeConverter; public class Test { //Sample method to validate and read the JWT private static void parseJWT(String jwt) { String a = "string"; //This line will throw an exception if it is not a signed JWS (as expected) Claims claims = Jwts.parser() .setSigningKey(DatatypeConverter.parseBase64Binary(a)) .parseClaimsJws(jwt).getBody(); System.out.println("ID: " + claims.getId()); System.out.println("Subject: " + claims.getSubject()); System.out.println("Issuer: " + claims.getIssuer()); System.out.println("Expiration: " + claims.getExpiration()); } //Sample method to construct a JWT private static String createJWT(String id, String issuer, String subject, long ttlMillis) { //The JWT signature algorithm we will be using to sign the token SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256; long nowMillis = System.currentTimeMillis(); Date now = new Date(nowMillis); String a = "string"; //We will sign our JWT with our ApiKey secret byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(a); Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName()); //Let's set the JWT Claims JwtBuilder builder = Jwts.builder().setId(id) .setIssuedAt(now) .setSubject(subject) .setIssuer(issuer) .signWith(signatureAlgorithm, signingKey); //if it has been specified, let's add the expiration if (ttlMillis >= 0) { long expMillis = nowMillis + ttlMillis; Date exp = new Date(expMillis); builder.setExpiration(exp); } //Builds the JWT and serializes it to a compact, URL-safe string return builder.compact(); } public static void main(String[] args) { String id = "1"; String issuer = "sxjd"; String subject = "steven"; long ttlMillis = 10000l; String jwt = createJWT(id, issuer, subject, ttlMillis); System.out.println(jwt); parseJWT(jwt); } // We need a signing key, so we'll create one just for this example. Usually // the key would be read from your application configuration instead. // Key key = MacProvider.generateKey(); // System.out.println(key.getEncoded()); // // String compactJws = Jwts.builder() // .setSubject("Joe") // .signWith(SignatureAlgorithm.HS512, key) // .compact(); // System.out.println(compactJws); // // System.out.println(Jwts.parser().setSigningKey(key). // parseClaimsJws(compactJws).getBody().getSubject().equals("Joe")); // // try { // // Jwts.parser().setSigningKey(key).parseClaimsJws(compactJws); // // //OK, we can trust this JWT // // } catch (SignatureException e) { // // //don't trust the JWT! // } // } }
UTF-8
Java
3,179
java
Test.java
Java
[ { "context": "1\";\n\t\tString issuer = \"sxjd\";\n\t\tString subject = \"steven\";\n\t\tlong ttlMillis = 10000l;\n\t\tString jwt = creat", "end": 2289, "score": 0.9983571767807007, "start": 2283, "tag": "NAME", "value": "steven" } ]
null
[]
package test; import io.jsonwebtoken.JwtBuilder; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import java.security.Key; import java.util.Date; import io.jsonwebtoken.Claims; import javax.crypto.spec.SecretKeySpec; import javax.xml.bind.DatatypeConverter; public class Test { //Sample method to validate and read the JWT private static void parseJWT(String jwt) { String a = "string"; //This line will throw an exception if it is not a signed JWS (as expected) Claims claims = Jwts.parser() .setSigningKey(DatatypeConverter.parseBase64Binary(a)) .parseClaimsJws(jwt).getBody(); System.out.println("ID: " + claims.getId()); System.out.println("Subject: " + claims.getSubject()); System.out.println("Issuer: " + claims.getIssuer()); System.out.println("Expiration: " + claims.getExpiration()); } //Sample method to construct a JWT private static String createJWT(String id, String issuer, String subject, long ttlMillis) { //The JWT signature algorithm we will be using to sign the token SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256; long nowMillis = System.currentTimeMillis(); Date now = new Date(nowMillis); String a = "string"; //We will sign our JWT with our ApiKey secret byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(a); Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName()); //Let's set the JWT Claims JwtBuilder builder = Jwts.builder().setId(id) .setIssuedAt(now) .setSubject(subject) .setIssuer(issuer) .signWith(signatureAlgorithm, signingKey); //if it has been specified, let's add the expiration if (ttlMillis >= 0) { long expMillis = nowMillis + ttlMillis; Date exp = new Date(expMillis); builder.setExpiration(exp); } //Builds the JWT and serializes it to a compact, URL-safe string return builder.compact(); } public static void main(String[] args) { String id = "1"; String issuer = "sxjd"; String subject = "steven"; long ttlMillis = 10000l; String jwt = createJWT(id, issuer, subject, ttlMillis); System.out.println(jwt); parseJWT(jwt); } // We need a signing key, so we'll create one just for this example. Usually // the key would be read from your application configuration instead. // Key key = MacProvider.generateKey(); // System.out.println(key.getEncoded()); // // String compactJws = Jwts.builder() // .setSubject("Joe") // .signWith(SignatureAlgorithm.HS512, key) // .compact(); // System.out.println(compactJws); // // System.out.println(Jwts.parser().setSigningKey(key). // parseClaimsJws(compactJws).getBody().getSubject().equals("Joe")); // // try { // // Jwts.parser().setSigningKey(key).parseClaimsJws(compactJws); // // //OK, we can trust this JWT // // } catch (SignatureException e) { // // //don't trust the JWT! // } // } }
3,179
0.648946
0.643599
96
32.114582
25.005362
93
false
false
0
0
0
0
0
0
1.989583
false
false
13
73347c20c2977e6a3d7554568242ea2222bb54f1
26,018,911,911,413
27f4ef410483ca9e5553ea6df5453c7d8eee6ac4
/src/java/Mapeos/Usuario.java
f9254ebbe1a14ae6e32bfb31dfa1c82937f5ac5b
[]
no_license
AlejandroMuralles/Guatefutbol
https://github.com/AlejandroMuralles/Guatefutbol
d0a41d8f56b47d6bc8eec5a9602b734b928c8c58
65f4bb183546474f5ceaddfd0447cc50ef1973bf
refs/heads/master
2016-08-08T05:07:05.503000
2015-11-10T15:24:45
2015-11-10T15:24:45
26,588,446
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Mapeos; // Generated 30-oct-2014 8:23:29 by Hibernate Tools 3.6.0 import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; /** * Usuario generated by hbm2java */ @Entity @Table(name="usuario" ,catalog="guatefut_liga" ) public class Usuario implements java.io.Serializable { private String username; private RolUsuario rolUsuario; private String password; public Usuario() { } public Usuario(String username, RolUsuario rolUsuario, String password) { this.username = username; this.rolUsuario = rolUsuario; this.password = password; } @Id @Column(name="username", unique=true, nullable=false, length=20) public String getUsername() { return this.username; } public void setUsername(String username) { this.username = username; } @ManyToOne(fetch=FetchType.EAGER) @JoinColumn(name="rol_usuario", nullable=false) public RolUsuario getRolUsuario() { return this.rolUsuario; } public void setRolUsuario(RolUsuario rolUsuario) { this.rolUsuario = rolUsuario; } @Column(name="password", nullable=false, length=50) public String getPassword() { return this.password; } public void setPassword(String password) { this.password = password; } }
UTF-8
Java
1,539
java
Usuario.java
Java
[ { "context": "Usuario, String password) {\n this.username = username;\n this.rolUsuario = rolUsuario;\n this", "end": 709, "score": 0.9968536496162415, "start": 701, "tag": "USERNAME", "value": "username" }, { "context": "is.rolUsuario = rolUsuario;\n this.pas...
null
[]
package Mapeos; // Generated 30-oct-2014 8:23:29 by Hibernate Tools 3.6.0 import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; /** * Usuario generated by hbm2java */ @Entity @Table(name="usuario" ,catalog="guatefut_liga" ) public class Usuario implements java.io.Serializable { private String username; private RolUsuario rolUsuario; private String password; public Usuario() { } public Usuario(String username, RolUsuario rolUsuario, String password) { this.username = username; this.rolUsuario = rolUsuario; this.password = <PASSWORD>; } @Id @Column(name="username", unique=true, nullable=false, length=20) public String getUsername() { return this.username; } public void setUsername(String username) { this.username = username; } @ManyToOne(fetch=FetchType.EAGER) @JoinColumn(name="rol_usuario", nullable=false) public RolUsuario getRolUsuario() { return this.rolUsuario; } public void setRolUsuario(RolUsuario rolUsuario) { this.rolUsuario = rolUsuario; } @Column(name="password", nullable=false, length=50) public String getPassword() { return this.password; } public void setPassword(String password) { this.password = <PASSWORD>; } }
1,543
0.675114
0.662768
71
20.647888
19.679186
77
false
false
0
0
0
0
0
0
0.408451
false
false
13
869d5916cd5f23e6d61dd24617ca707a86fb42d4
26,018,911,911,761
b28776956f3566a9c6d15bc748eb663e127f79a9
/Lab6/Server/TCPServer/TCPServerSender.java
bc6f21aa0d13b5e0356ed2e2d4509d6adea7425a
[]
no_license
ThanhPham1003/Pro
https://github.com/ThanhPham1003/Pro
c961a005401531ecab79edb0d42a98262b3f9a1c
75509305ce4664b8b9f7f95983b41305c6a8a3cf
refs/heads/master
2022-11-21T03:55:02.753000
2022-11-13T19:11:27
2022-11-13T19:11:27
248,085,411
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package TCPServer; import Commands.*; import java.io.IOException; import java.io.ObjectOutputStream; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.nio.channels.SocketChannel; import java.util.HashMap; public class TCPServerSender implements Runnable { private String str; private ServerSocket ss; private HashMap<String, AbstractCommand> availableCommands = new HashMap<>(); public TCPServerSender(String str,ServerSocket ss ) throws IOException { this.str =str; this.ss =ss; }; public HashMap<String, AbstractCommand> getCommand() { return availableCommands; } /** *Run to send data to client. */ @Override public void run() { try { Socket s = ss.accept(); ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream()); oos.writeObject(str); oos.flush(); } catch (IOException e) { System.out.println("Data tranfer error" + e.getMessage()); } } }
UTF-8
Java
1,120
java
TCPServerSender.java
Java
[]
null
[]
package TCPServer; import Commands.*; import java.io.IOException; import java.io.ObjectOutputStream; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.nio.channels.SocketChannel; import java.util.HashMap; public class TCPServerSender implements Runnable { private String str; private ServerSocket ss; private HashMap<String, AbstractCommand> availableCommands = new HashMap<>(); public TCPServerSender(String str,ServerSocket ss ) throws IOException { this.str =str; this.ss =ss; }; public HashMap<String, AbstractCommand> getCommand() { return availableCommands; } /** *Run to send data to client. */ @Override public void run() { try { Socket s = ss.accept(); ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream()); oos.writeObject(str); oos.flush(); } catch (IOException e) { System.out.println("Data tranfer error" + e.getMessage()); } } }
1,120
0.628571
0.628571
41
25.317074
21.979412
81
false
false
0
0
0
0
0
0
0.585366
false
false
13
0f4b088bce7c6f4e24dfb7581a686cbb057653ca
22,402,549,444,918
53c89b429f99095a5ff7ac2d962a266f18efb314
/src/nopbundle/NopBundleConfiguration.java
9740ba2777733183fe318e75576214c4df77dd8a
[]
no_license
adharmad/nop-icf-bundle
https://github.com/adharmad/nop-icf-bundle
5c25987e1b0110733a3303e590fbda2a96165423
f5c911902f584dec6154f0ec3baab769e28b37a4
refs/heads/master
2021-01-13T09:44:21.825000
2016-09-21T22:53:12
2016-09-21T22:53:12
68,863,689
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package nopbundle; import org.identityconnectors.framework.spi.AbstractConfiguration; public class NopBundleConfiguration extends AbstractConfiguration { private String strConfigParam; private boolean strict = false; public boolean isStrict() { return strict; } public void setStrict(boolean strict) { this.strict = strict; } public void validate() { } public String getStrConfigParam() { return strConfigParam; } public void setStrConfigParam(String strConfigParam) { this.strConfigParam = strConfigParam; } }
UTF-8
Java
590
java
NopBundleConfiguration.java
Java
[]
null
[]
package nopbundle; import org.identityconnectors.framework.spi.AbstractConfiguration; public class NopBundleConfiguration extends AbstractConfiguration { private String strConfigParam; private boolean strict = false; public boolean isStrict() { return strict; } public void setStrict(boolean strict) { this.strict = strict; } public void validate() { } public String getStrConfigParam() { return strConfigParam; } public void setStrConfigParam(String strConfigParam) { this.strConfigParam = strConfigParam; } }
590
0.705085
0.705085
31
18.032259
20.430029
67
false
false
0
0
0
0
0
0
0.516129
false
false
13
9bff8306ca64f1705f62e3ff9dc1e71f3e0d8074
33,036,888,455,992
b13533a0186e8314f62eee5b395f4debe32912ee
/Serialization/src/com/serialization/customization/DeSerializeEmployee.java
fcf3c87106fb3e49471db27b6f89d0a4ca42bd2f
[]
no_license
rahul7990/rahulJavaRepo
https://github.com/rahul7990/rahulJavaRepo
c1b687ca6a4df23ff54a6f0c8c853049eafe10d9
fff7ef8a2d13e946bc444c82760f1b03970110a4
refs/heads/master
2021-01-01T03:41:52.431000
2017-03-02T09:47:06
2017-03-02T09:47:06
77,312,971
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.serialization.customization; import java.io.FileInputStream; import java.io.IOException; import java.io.ObjectInputStream; public class DeSerializeEmployee { public static void main(String[] args) { try { Employee emp; FileInputStream fin = new FileInputStream("Employee.txt"); ObjectInputStream objinp = new ObjectInputStream(fin); Object obj; while (!((obj = objinp.readObject()) instanceof EndOfFileIndecator)) { emp = (Employee)obj; System.out.println(emp); } objinp.close(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } System.out.println("Object DeSerialization completed."); } }
UTF-8
Java
745
java
DeSerializeEmployee.java
Java
[]
null
[]
package com.serialization.customization; import java.io.FileInputStream; import java.io.IOException; import java.io.ObjectInputStream; public class DeSerializeEmployee { public static void main(String[] args) { try { Employee emp; FileInputStream fin = new FileInputStream("Employee.txt"); ObjectInputStream objinp = new ObjectInputStream(fin); Object obj; while (!((obj = objinp.readObject()) instanceof EndOfFileIndecator)) { emp = (Employee)obj; System.out.println(emp); } objinp.close(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } System.out.println("Object DeSerialization completed."); } }
745
0.684564
0.684564
34
20.911764
20.753975
73
false
false
0
0
0
0
0
0
1.735294
false
false
13
4f5a4824222fb17cea58a6319970f54ceb64deb2
9,509,057,610,429
dd806ed8bffbf7e9baa1d55c421248b007e96744
/app/front-end/app/src/main/java/e/iot/betbuddy/GroupFragment.java
eb798c8b7094f2db1a341c4a7ae170e727ae043a
[]
no_license
bet-buddy/BetBuddy
https://github.com/bet-buddy/BetBuddy
03a04578232a99b5d2203c387aebd5f70e21a57b
e8d8860b6d90d8776ff5369c454150b7c185d1be
refs/heads/master
2020-04-26T17:10:00.724000
2019-04-16T23:54:03
2019-04-16T23:54:03
173,704,568
0
1
null
false
2019-03-24T21:23:11
2019-03-04T08:30:20
2019-03-24T21:21:42
2019-03-24T21:23:10
7,293
0
0
0
Java
false
null
package e.iot.betbuddy; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; import e.iot.betbuddy.adapters.GroupAdapter; import e.iot.betbuddy.data.DataHolder; import e.iot.betbuddy.model.Group; import e.iot.betbuddy.model.User; public class GroupFragment extends Fragment { @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_group, container, false); ListView groupListView = view.findViewById(R.id.group_ListView); GroupAdapter groupAdapter = new GroupAdapter(this.getActivity()); groupListView.setAdapter(groupAdapter); groupListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { User user = (User)(DataHolder.getInstance().retrieve("user")); Group group = user.getGroupList().get(position); DataHolder.getInstance().save("group",group); startActivity(new Intent(getActivity(), MessageActivity.class)); } }); return view; } }
UTF-8
Java
1,555
java
GroupFragment.java
Java
[]
null
[]
package e.iot.betbuddy; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; import e.iot.betbuddy.adapters.GroupAdapter; import e.iot.betbuddy.data.DataHolder; import e.iot.betbuddy.model.Group; import e.iot.betbuddy.model.User; public class GroupFragment extends Fragment { @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_group, container, false); ListView groupListView = view.findViewById(R.id.group_ListView); GroupAdapter groupAdapter = new GroupAdapter(this.getActivity()); groupListView.setAdapter(groupAdapter); groupListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { User user = (User)(DataHolder.getInstance().retrieve("user")); Group group = user.getGroupList().get(position); DataHolder.getInstance().save("group",group); startActivity(new Intent(getActivity(), MessageActivity.class)); } }); return view; } }
1,555
0.717685
0.717042
41
36.92683
30.515402
132
false
false
0
0
0
0
0
0
0.829268
false
false
13
0ab159d0f4ae4c4724eb98a26c4d9ab921ddd4d4
1,958,505,117,827
f55225181830495700f2f2353619e61bcc37d757
/Soba/src/UnosSobeGUI.java
019f955298ba55808379db665c66c86d2929e9e2
[]
no_license
markotikvic/hostel_gui_java_coded
https://github.com/markotikvic/hostel_gui_java_coded
6e1575c07d6f7ad087b1dfd942df228f6a2d0342
c2f52a1ed1482c5b759548252a23b7e86f4a902d
refs/heads/master
2015-08-09T15:26:59.945000
2013-11-30T01:34:06
2013-11-30T01:34:06
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.awt.Canvas; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.WindowEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.rmi.UnexpectedException; import javax.swing.ComboBoxModel; import javax.swing.DefaultComboBoxModel; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JTextField; import javax.swing.WindowConstants; import javax.swing.SwingUtilities; import com.toedter.calendar.JDateChooser; /** * This code was edited or generated using CloudGarden's Jigloo * SWT/Swing GUI Builder, which is free for non-commercial * use. If Jigloo is being used commercially (ie, by a corporation, * company or business for any purpose whatever) then you * should purchase a license for each developer using Jigloo. * Please visit www.cloudgarden.com for details. * Use of Jigloo implies acceptance of these licensing terms. * A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR * THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED * LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE. * @param <GUI> */ public class UnosSobeGUI extends javax.swing.JFrame { private JLabel LabelaBrojSobe; private JLabel LabelaBojeSobe; private JLabel LabelaBrKreveta; private JButton UnosNoveSobeZavrsen; private JComboBox ComboTV; private JButton ExitUnosNoveSobeBezCuvanja; private JDialog ProzorZaGreskuBrojaSobe; private JComboBox ComboOrmar; private JComboBox ComboBrKreveta; private JComboBox ComboBoje; private JTextField PoljeZaCenuSobe; private JTextField PoljeZaBrojSobe; private JLabel LabelaImaTV; private JLabel LabelaImaOrmar; private JLabel LabelaCenaSobe; public HostelGUI parentForma; /** * Auto-generated main method to display this JFrame */ public UnosSobeGUI() { super(); initGUI(); } public UnosSobeGUI(HostelGUI forma) { super(); parentForma=forma; initGUI(); } private void initGUI() { try { setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); getContentPane().setLayout(null); { LabelaBrojSobe = new JLabel(); getContentPane().add(LabelaBrojSobe); LabelaBrojSobe.setText("BrojSobe"); LabelaBrojSobe.setBounds(12, 12, 63, 15); } { LabelaBojeSobe = new JLabel(); getContentPane().add(LabelaBojeSobe); LabelaBojeSobe.setText("BojaSobe"); LabelaBojeSobe.setBounds(87, 12, 65, 15); } { LabelaBrKreveta = new JLabel(); getContentPane().add(LabelaBrKreveta); LabelaBrKreveta.setText("BrojKreveta"); LabelaBrKreveta.setBounds(165, 12, 79, 15); } { LabelaCenaSobe = new JLabel(); getContentPane().add(LabelaCenaSobe); LabelaCenaSobe.setText("CenaSobe"); LabelaCenaSobe.setBounds(250, 12, 76, 15); } { LabelaImaOrmar = new JLabel(); getContentPane().add(LabelaImaOrmar); LabelaImaOrmar.setText("Ormar"); LabelaImaOrmar.setBounds(329, 12, 76, 14); } { LabelaImaTV = new JLabel(); getContentPane().add(LabelaImaTV); LabelaImaTV.setText("TV"); LabelaImaTV.setBounds(417, 12, 84, 15); } { PoljeZaBrojSobe = new JTextField(); getContentPane().add(PoljeZaBrojSobe); PoljeZaBrojSobe.setBounds(12, 47, 63, 22); PoljeZaBrojSobe.setText("0"); } { PoljeZaCenuSobe = new JTextField(); getContentPane().add(PoljeZaCenuSobe); PoljeZaCenuSobe.setBounds(250, 47, 65, 22); PoljeZaCenuSobe.setText("0"); } { ComboBoxModel ComboBojeModel = new DefaultComboBoxModel( new String[] { "Bela", "Zuta", "Krem" }); ComboBoje = new JComboBox(); getContentPane().add(ComboBoje); ComboBoje.setModel(ComboBojeModel); ComboBoje.setBounds(87, 46, 65, 22); } { ComboBoxModel ComboBrKrevetaModel = new DefaultComboBoxModel( new String[] { "1", "2", "3", "4" }); ComboBrKreveta = new JComboBox(); getContentPane().add(ComboBrKreveta); ComboBrKreveta.setModel(ComboBrKrevetaModel); ComboBrKreveta.setBounds(164, 46, 63, 22); } { ComboBoxModel ComboOrmarModel = new DefaultComboBoxModel( new String[] { "Da", "Ne" }); ComboOrmar = new JComboBox(); getContentPane().add(ComboOrmar); ComboOrmar.setModel(ComboOrmarModel); ComboOrmar.setBounds(327, 46, 78, 22); } { ComboBoxModel ComboTVModel = new DefaultComboBoxModel( new String[] { "Da", "Ne" }); ComboTV = new JComboBox(); getContentPane().add(ComboTV); ComboTV.setModel(ComboTVModel); ComboTV.setBounds(417, 46, 84, 22); } { UnosNoveSobeZavrsen = new JButton(); getContentPane().add(UnosNoveSobeZavrsen); UnosNoveSobeZavrsen.setText("Prihvati"); UnosNoveSobeZavrsen.setBounds(12, 222, 135, 22); UnosNoveSobeZavrsen.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent evt) { UnosNoveSobeZavrsenMouseClicked(evt); } }); } { ExitUnosNoveSobeBezCuvanja = new JButton(); getContentPane().add(ExitUnosNoveSobeBezCuvanja); ExitUnosNoveSobeBezCuvanja.setText("Otkazi"); ExitUnosNoveSobeBezCuvanja.setBounds(382, 222, 129, 21); ExitUnosNoveSobeBezCuvanja.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent evt) { ExitUnosNoveSobeBezCuvanjaMouseClicked(evt); } }); } pack(); this.setSize(535, 315); } catch (Exception e) { //add your error handling code here e.printStackTrace(); } } private void thisWindowClosed(WindowEvent evt) { System.out.println("this.windowClosed, event="+evt); //TODO add your code for this.windowClosed parentForma.enable(true); parentForma.show(); } private void UnosNoveSobeZavrsenMouseClicked(MouseEvent evt) { System.out.println("UnosNoveSobeZavrsen.mouseClicked, event="+evt); //TODO add your code for UnosNoveSobeZavrsen.mouseClicked int opsegB=0; int opsegC=0; int brSobe = Integer.parseInt(PoljeZaBrojSobe.getText()); if(brSobe>=parentForma.mojHostel.ukupanBrSoba || brSobe<0) { opsegB=1; System.out.println("Unesite broj sobe u opsegu 0-250"); } float cenaSobe = Float.parseFloat(PoljeZaCenuSobe.getText()); if(cenaSobe<=0 && cenaSobe>=10000) { opsegC=1; } else { opsegC=0; } if(opsegB==0 && opsegC==0) { String bojaSobeString = (String) ComboBoje.getSelectedItem(); short brojKreveta = Short.parseShort((String) ComboBrKreveta.getSelectedItem()); String imaLiOrmar = (String) ComboOrmar.getSelectedItem(); String imaLiTV = (String) ComboTV.getSelectedItem(); parentForma.UnesiNovuSobuUTabelu(brSobe, bojaSobeString, brojKreveta, cenaSobe, imaLiOrmar, imaLiTV); parentForma.enable(true); parentForma.show(); this.dispose(); } } private void ExitUnosNoveSobeBezCuvanjaMouseClicked(MouseEvent evt) { System.out.println("ExitUnosNoveSobeBezCuvanja.mouseClicked, event="+evt); //TODO add your code for ExitUnosNoveSobeBezCuvanja.mouseClicked parentForma.enable(true); parentForma.show(); this.dispose(); } }
UTF-8
Java
7,116
java
UnosSobeGUI.java
Java
[]
null
[]
import java.awt.Canvas; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.WindowEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.rmi.UnexpectedException; import javax.swing.ComboBoxModel; import javax.swing.DefaultComboBoxModel; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JTextField; import javax.swing.WindowConstants; import javax.swing.SwingUtilities; import com.toedter.calendar.JDateChooser; /** * This code was edited or generated using CloudGarden's Jigloo * SWT/Swing GUI Builder, which is free for non-commercial * use. If Jigloo is being used commercially (ie, by a corporation, * company or business for any purpose whatever) then you * should purchase a license for each developer using Jigloo. * Please visit www.cloudgarden.com for details. * Use of Jigloo implies acceptance of these licensing terms. * A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR * THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED * LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE. * @param <GUI> */ public class UnosSobeGUI extends javax.swing.JFrame { private JLabel LabelaBrojSobe; private JLabel LabelaBojeSobe; private JLabel LabelaBrKreveta; private JButton UnosNoveSobeZavrsen; private JComboBox ComboTV; private JButton ExitUnosNoveSobeBezCuvanja; private JDialog ProzorZaGreskuBrojaSobe; private JComboBox ComboOrmar; private JComboBox ComboBrKreveta; private JComboBox ComboBoje; private JTextField PoljeZaCenuSobe; private JTextField PoljeZaBrojSobe; private JLabel LabelaImaTV; private JLabel LabelaImaOrmar; private JLabel LabelaCenaSobe; public HostelGUI parentForma; /** * Auto-generated main method to display this JFrame */ public UnosSobeGUI() { super(); initGUI(); } public UnosSobeGUI(HostelGUI forma) { super(); parentForma=forma; initGUI(); } private void initGUI() { try { setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); getContentPane().setLayout(null); { LabelaBrojSobe = new JLabel(); getContentPane().add(LabelaBrojSobe); LabelaBrojSobe.setText("BrojSobe"); LabelaBrojSobe.setBounds(12, 12, 63, 15); } { LabelaBojeSobe = new JLabel(); getContentPane().add(LabelaBojeSobe); LabelaBojeSobe.setText("BojaSobe"); LabelaBojeSobe.setBounds(87, 12, 65, 15); } { LabelaBrKreveta = new JLabel(); getContentPane().add(LabelaBrKreveta); LabelaBrKreveta.setText("BrojKreveta"); LabelaBrKreveta.setBounds(165, 12, 79, 15); } { LabelaCenaSobe = new JLabel(); getContentPane().add(LabelaCenaSobe); LabelaCenaSobe.setText("CenaSobe"); LabelaCenaSobe.setBounds(250, 12, 76, 15); } { LabelaImaOrmar = new JLabel(); getContentPane().add(LabelaImaOrmar); LabelaImaOrmar.setText("Ormar"); LabelaImaOrmar.setBounds(329, 12, 76, 14); } { LabelaImaTV = new JLabel(); getContentPane().add(LabelaImaTV); LabelaImaTV.setText("TV"); LabelaImaTV.setBounds(417, 12, 84, 15); } { PoljeZaBrojSobe = new JTextField(); getContentPane().add(PoljeZaBrojSobe); PoljeZaBrojSobe.setBounds(12, 47, 63, 22); PoljeZaBrojSobe.setText("0"); } { PoljeZaCenuSobe = new JTextField(); getContentPane().add(PoljeZaCenuSobe); PoljeZaCenuSobe.setBounds(250, 47, 65, 22); PoljeZaCenuSobe.setText("0"); } { ComboBoxModel ComboBojeModel = new DefaultComboBoxModel( new String[] { "Bela", "Zuta", "Krem" }); ComboBoje = new JComboBox(); getContentPane().add(ComboBoje); ComboBoje.setModel(ComboBojeModel); ComboBoje.setBounds(87, 46, 65, 22); } { ComboBoxModel ComboBrKrevetaModel = new DefaultComboBoxModel( new String[] { "1", "2", "3", "4" }); ComboBrKreveta = new JComboBox(); getContentPane().add(ComboBrKreveta); ComboBrKreveta.setModel(ComboBrKrevetaModel); ComboBrKreveta.setBounds(164, 46, 63, 22); } { ComboBoxModel ComboOrmarModel = new DefaultComboBoxModel( new String[] { "Da", "Ne" }); ComboOrmar = new JComboBox(); getContentPane().add(ComboOrmar); ComboOrmar.setModel(ComboOrmarModel); ComboOrmar.setBounds(327, 46, 78, 22); } { ComboBoxModel ComboTVModel = new DefaultComboBoxModel( new String[] { "Da", "Ne" }); ComboTV = new JComboBox(); getContentPane().add(ComboTV); ComboTV.setModel(ComboTVModel); ComboTV.setBounds(417, 46, 84, 22); } { UnosNoveSobeZavrsen = new JButton(); getContentPane().add(UnosNoveSobeZavrsen); UnosNoveSobeZavrsen.setText("Prihvati"); UnosNoveSobeZavrsen.setBounds(12, 222, 135, 22); UnosNoveSobeZavrsen.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent evt) { UnosNoveSobeZavrsenMouseClicked(evt); } }); } { ExitUnosNoveSobeBezCuvanja = new JButton(); getContentPane().add(ExitUnosNoveSobeBezCuvanja); ExitUnosNoveSobeBezCuvanja.setText("Otkazi"); ExitUnosNoveSobeBezCuvanja.setBounds(382, 222, 129, 21); ExitUnosNoveSobeBezCuvanja.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent evt) { ExitUnosNoveSobeBezCuvanjaMouseClicked(evt); } }); } pack(); this.setSize(535, 315); } catch (Exception e) { //add your error handling code here e.printStackTrace(); } } private void thisWindowClosed(WindowEvent evt) { System.out.println("this.windowClosed, event="+evt); //TODO add your code for this.windowClosed parentForma.enable(true); parentForma.show(); } private void UnosNoveSobeZavrsenMouseClicked(MouseEvent evt) { System.out.println("UnosNoveSobeZavrsen.mouseClicked, event="+evt); //TODO add your code for UnosNoveSobeZavrsen.mouseClicked int opsegB=0; int opsegC=0; int brSobe = Integer.parseInt(PoljeZaBrojSobe.getText()); if(brSobe>=parentForma.mojHostel.ukupanBrSoba || brSobe<0) { opsegB=1; System.out.println("Unesite broj sobe u opsegu 0-250"); } float cenaSobe = Float.parseFloat(PoljeZaCenuSobe.getText()); if(cenaSobe<=0 && cenaSobe>=10000) { opsegC=1; } else { opsegC=0; } if(opsegB==0 && opsegC==0) { String bojaSobeString = (String) ComboBoje.getSelectedItem(); short brojKreveta = Short.parseShort((String) ComboBrKreveta.getSelectedItem()); String imaLiOrmar = (String) ComboOrmar.getSelectedItem(); String imaLiTV = (String) ComboTV.getSelectedItem(); parentForma.UnesiNovuSobuUTabelu(brSobe, bojaSobeString, brojKreveta, cenaSobe, imaLiOrmar, imaLiTV); parentForma.enable(true); parentForma.show(); this.dispose(); } } private void ExitUnosNoveSobeBezCuvanjaMouseClicked(MouseEvent evt) { System.out.println("ExitUnosNoveSobeBezCuvanja.mouseClicked, event="+evt); //TODO add your code for ExitUnosNoveSobeBezCuvanja.mouseClicked parentForma.enable(true); parentForma.show(); this.dispose(); } }
7,116
0.712901
0.691119
253
27.126482
21.050097
103
false
false
0
0
0
0
0
0
3.193676
false
false
13
1c15f1883fbed031d5378c9331622f30a02c1dfd
26,645,977,144,581
689c57a04de8871f822a05dc1ae0b3f5893a20cf
/app/src/main/java/com/turingoal/bts/dispatch/ui/adapter/MaintenanceWorkPositionAdapter.java
62a366a6452e3a5e11cc91d7c502063681e5419c
[]
no_license
feng19960223/tg-bts-dispatch-app
https://github.com/feng19960223/tg-bts-dispatch-app
011d08877b4675a18f1530dcbdaffc40b4a1b946
439bcdbf2e765fa42ccaf7b454fce9f219eb4960
refs/heads/master
2020-04-05T14:29:46.539000
2018-11-10T00:13:00
2018-11-10T00:13:00
156,931,918
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.turingoal.bts.dispatch.ui.adapter; import android.text.TextUtils; import com.chad.library.adapter.base.BaseQuickAdapter; import com.chad.library.adapter.base.BaseViewHolder; import com.turingoal.bts.dispatch.R; import com.turingoal.bts.dispatch.bean.MaintenanceWorkPositionBean; /** * 任务管理详情adapter */ public class MaintenanceWorkPositionAdapter extends BaseQuickAdapter<MaintenanceWorkPositionBean, BaseViewHolder> { public MaintenanceWorkPositionAdapter() { super(R.layout.item_mintenance_work_position); } @Override protected void convert(final BaseViewHolder holder, final MaintenanceWorkPositionBean maintenanceWorkPositionBean) { holder.setText(R.id.tvWorkNum, "" + maintenanceWorkPositionBean.getWorkNum()) .setText(R.id.tvName, TextUtils.isEmpty(maintenanceWorkPositionBean.getName()) ? "点击选择人员" : maintenanceWorkPositionBean.getName()); holder.addOnClickListener(R.id.llPosition); } }
UTF-8
Java
997
java
MaintenanceWorkPositionAdapter.java
Java
[]
null
[]
package com.turingoal.bts.dispatch.ui.adapter; import android.text.TextUtils; import com.chad.library.adapter.base.BaseQuickAdapter; import com.chad.library.adapter.base.BaseViewHolder; import com.turingoal.bts.dispatch.R; import com.turingoal.bts.dispatch.bean.MaintenanceWorkPositionBean; /** * 任务管理详情adapter */ public class MaintenanceWorkPositionAdapter extends BaseQuickAdapter<MaintenanceWorkPositionBean, BaseViewHolder> { public MaintenanceWorkPositionAdapter() { super(R.layout.item_mintenance_work_position); } @Override protected void convert(final BaseViewHolder holder, final MaintenanceWorkPositionBean maintenanceWorkPositionBean) { holder.setText(R.id.tvWorkNum, "" + maintenanceWorkPositionBean.getWorkNum()) .setText(R.id.tvName, TextUtils.isEmpty(maintenanceWorkPositionBean.getName()) ? "点击选择人员" : maintenanceWorkPositionBean.getName()); holder.addOnClickListener(R.id.llPosition); } }
997
0.776978
0.776978
25
37.919998
41.457371
147
false
false
0
0
0
0
0
0
0.52
false
false
13
ddf2102d22fa99052d08a9cba939f48e1d693344
31,817,117,760,633
72c637102a2b67eab3517205d301e9a175ddbeaa
/src/MinimumSubarray.java
346c9c67ad381a0c5313b896044c3c8a4b8eefa9
[]
no_license
Shuxuan/LeetCode_Algorithm
https://github.com/Shuxuan/LeetCode_Algorithm
57d43b5530d32da644914f990a5f89303102913f
8a250b63d7db3bf1a95a015bfdf8dc689d69eb96
refs/heads/master
2016-06-02T12:42:26.241000
2015-12-14T23:54:08
2015-12-14T23:54:08
40,466,945
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.ArrayList; public class MinimumSubarray { public MinimumSubarray() { // TODO Auto-generated constructor stub } public int minSubArray(ArrayList<Integer> nums) { // write your code if (nums == null || nums.size() == 0){ return 0; } int maxSum = 0; int min = Integer.MAX_VALUE; int sum = 0; int size = nums.size(); for (int i = 0; i < size; i++){ System.out.println("num.get(i): " + nums.get(i)); sum += nums.get(i); System.out.println("sum: " + sum); min = Math.min(min, sum - maxSum); System.out.println("min: " + min); maxSum = Math.max(maxSum, sum); System.out.println("maxSum: " + maxSum); } return min; } public static void main(String[] args) { // TODO Auto-generated method stub ArrayList<Integer> nums = new ArrayList<Integer>(); nums.add(1); nums.add(-1); nums.add(-2); nums.add(1); MinimumSubarray obj = new MinimumSubarray(); obj.minSubArray(nums); } }
UTF-8
Java
1,101
java
MinimumSubarray.java
Java
[]
null
[]
import java.util.ArrayList; public class MinimumSubarray { public MinimumSubarray() { // TODO Auto-generated constructor stub } public int minSubArray(ArrayList<Integer> nums) { // write your code if (nums == null || nums.size() == 0){ return 0; } int maxSum = 0; int min = Integer.MAX_VALUE; int sum = 0; int size = nums.size(); for (int i = 0; i < size; i++){ System.out.println("num.get(i): " + nums.get(i)); sum += nums.get(i); System.out.println("sum: " + sum); min = Math.min(min, sum - maxSum); System.out.println("min: " + min); maxSum = Math.max(maxSum, sum); System.out.println("maxSum: " + maxSum); } return min; } public static void main(String[] args) { // TODO Auto-generated method stub ArrayList<Integer> nums = new ArrayList<Integer>(); nums.add(1); nums.add(-1); nums.add(-2); nums.add(1); MinimumSubarray obj = new MinimumSubarray(); obj.minSubArray(nums); } }
1,101
0.542234
0.53406
44
24.022728
18.105108
58
false
false
0
0
0
0
0
0
1.181818
false
false
13
9eabba4da9e01494b84023aa2fec4cc041d4f080
4,750,233,857,290
103e24844688bdcabdf943ad49b4a71a454ee468
/src/main/java/com/rjxx/taxeasy/dal/JyxxsqService.java
def2070896cd11cb0feb691464f865af0c670b35
[]
no_license
leaveneaos/kpt_svc-
https://github.com/leaveneaos/kpt_svc-
0bbf8dbd5056b6fe3a0b4224f1a7faa6713104b8
6805710b2a91b14ca166769ec43801cbedd1f3ac
refs/heads/master
2020-09-30T12:07:58.361000
2018-08-30T02:47:33
2018-08-30T02:47:33
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.rjxx.taxeasy.dal; import com.rjxx.comm.mybatis.Pagination; import com.rjxx.taxeasy.dao.bo.*; import com.rjxx.taxeasy.dao.orm.JyxxsqJpaDao; import com.rjxx.taxeasy.dao.orm.JyxxsqMapper; import com.rjxx.taxeasy.dao.vo.JymxsqVo; import com.rjxx.taxeasy.dao.vo.JyxxsqVO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; /** * 由GenJavaCode类自动生成 * <p> * Wed Jan 04 13:33:08 CST 2017 * * @ZhangBing */ @Service public class JyxxsqService { @Autowired private JyxxsqJpaDao jyxxsqJpaDao; @Autowired private JyxxsqMapper jyxxsqMapper; @Autowired private JymxsqService jymxsqservice; @Autowired private JymxsqClService jymxsqClService; @Autowired private JyzfmxService jyzfmxService; public Jyxxsq findOne(int id) { return jyxxsqJpaDao.findOne(id); } public void save(Jyxxsq jyxxsq) { jyxxsqJpaDao.save(jyxxsq); } public void save(List<Jyxxsq> jyxxsqList) { jyxxsqJpaDao.save(jyxxsqList); } public Jyxxsq findOneByParams(Map params) { return jyxxsqMapper.findOneByParams(params); } public Jyxxsq findOneByTqmAndJshj(Map params) { return jyxxsqMapper.findOneByTqmAndJshj(params); } public List<Jyxxsq> findAllByTqms(Map params) { return jyxxsqMapper.findAllByTqms(params); } public List<Jyxxsq> findAllByJylshs(Map params) { return jyxxsqMapper.findAllByJylshs(params); } public Jyxxsq findSjlyAndOpenidByMap(Map params) { return jyxxsqMapper.findSjlyAndOpenidByMap(params); } public List<Jyxxsq> findAllByDdhs(Map params) { return jyxxsqMapper.findAllByDdhs(params); } public List<JyxxsqVO> findByPage(Pagination pagination) { return jyxxsqMapper.findByPage(pagination); } public List<Jyxxsq> findByPage1(Pagination pagination) { return jyxxsqMapper.findByPage1(pagination); } public List<Jyxxsq> findByMapParams(Map params) { return jyxxsqMapper.findByMapParams(params); } public Xf findXfExistByKpd(Map params) { return jyxxsqMapper.findXfExistByKpd(params); } public Xf findXfExistByXfsh(Map params) { return jyxxsqMapper.findXfExistByXfsh(params); } public void saveJyxxsq(Jyxxsq jyxxsq){ jyxxsqMapper.saveJyxxsq(jyxxsq); } public void addJyxxsqBatch(List<Jyxxsq> Jyxxsqs){ jyxxsqMapper.addJyxxsqBatch(Jyxxsqs); } public List<JyxxsqVO> findYscByPage(Pagination pagination){ return jyxxsqMapper.findYscByPage(pagination); } public void updateGfxx(Map params){ jyxxsqMapper.updateGfxx(params); } public List<JyxxsqVO> findByPage2(Map params) { return jyxxsqMapper.findByPage2(params); } public Integer findtotal(Map params) { return jyxxsqMapper.findtotal(params); } /** * 删除交易流水,包括明细 * * @param sqlshList */ @Transactional public void delBySqlshList(List<Integer> sqlshList) { Iterable<Jyxxsq> jylsIterable = jyxxsqJpaDao.findAll(sqlshList); jyxxsqJpaDao.delete(jylsIterable); List<Jymxsq> jymxsqList = jymxsqservice.findBySqlshList(sqlshList); jymxsqservice.delete(jymxsqList); } /** * 删除交易流水,包括明细以及处理明细 * * @param sqlshList */ @Transactional public void delBySqlshList2(List<Integer> sqlshList) { Iterable<Jyxxsq> jylsIterable = jyxxsqJpaDao.findAll(sqlshList); jyxxsqJpaDao.delete(jylsIterable); List<Jymxsq> jymxsqList = jymxsqservice.findBySqlshList(sqlshList); List<JymxsqCl> jymxsqCLList = jymxsqClService.findBySqlshList(sqlshList); jymxsqservice.delete(jymxsqList); jymxsqClService.delete(jymxsqCLList); } /** * 更新jyxxsq状态 * * @param sqlshList * @param clztdm */ public void updateJyxxsqZtzt(List<Integer> sqlshList, String ztbz) { List<Jyxxsq> jylsIterable = (List<Jyxxsq>) jyxxsqJpaDao.findAll(sqlshList); for (Jyxxsq jyxxsq : jylsIterable) { jyxxsq.setZtbz(ztbz); jyxxsq.setXgsj(new Date()); } save(jylsIterable); } /** * 保存交易信息申请 * * @param jyxxsq * @param jymxsqList */ @Transactional public Integer saveJyxxsq(Jyxxsq jyxxsq, List<Jymxsq> jymxsqList) { save(jyxxsq); int sqlsh = jyxxsq.getSqlsh(); for (Jymxsq Jymxsq : jymxsqList) { Jymxsq.setSqlsh(sqlsh); } jymxsqservice.save(jymxsqList); return sqlsh; } /** * 保存交易信息申请 * * @param jyxxsq * @param jymxsqList */ @Transactional public Integer saveJyxxsq(Jyxxsq jyxxsq, List<Jymxsq> jymxsqList,List<JymxsqCl> jymxsqClList,List<Jyzfmx> jyzfmxList) { save(jyxxsq); int sqlsh = jyxxsq.getSqlsh(); for (Jymxsq Jymxsq : jymxsqList) { Jymxsq.setSqlsh(sqlsh); } if(null != jymxsqClList && !jymxsqClList.isEmpty()){ for (JymxsqCl jymxsqCl : jymxsqClList) { jymxsqCl.setSqlsh(sqlsh); } jymxsqClService.save(jymxsqClList); } if(null != jyzfmxList && !jyzfmxList.isEmpty()){ for (Jyzfmx jyzfmx : jyzfmxList) { jyzfmx.setSqlsh(sqlsh); } jyzfmxService.save(jyzfmxList); } jymxsqservice.save(jymxsqList); return sqlsh; } /** * 交易信息申请与明细一对一 * * @param jyxxsqList * @param jymxsqList */ @Transactional public void saveAll(List<Jyxxsq> jyxxsqList, List<JymxsqVo> jymxsqList) { jyxxsqJpaDao.save(jyxxsqList); List<Jymxsq> mxList = new ArrayList<>(); Jymxsq mx = null; for (Jyxxsq jyxxsq : jyxxsqList) { for (JymxsqVo vo : jymxsqList) { if (jyxxsq.getDdh().equals(vo.getDdh())) { mx = getMx(vo); mx.setSqlsh(jyxxsq.getSqlsh()); mxList.add(mx); } } } jymxsqservice.save(mxList); } /** * 交易信息申请与明细一对一 * * @param jyxxsqList * @param jymxsqList * @param jymxsqClList * @param jyzfmxList */ @Transactional public void saveAll(List<Jyxxsq> jyxxsqList, List<Jymxsq> jymxsqList,List<JymxsqCl> jymxsqClList,List<Jyzfmx> jyzfmxList) throws Exception{ //jyxxsqJpaDao.save(jyxxsqList); addJyxxsqBatch(jyxxsqList); List<Jymxsq> mxList = new ArrayList<>(); Jymxsq mx = null; for (Jyxxsq jyxxsq : jyxxsqList) { for (Jymxsq vo : jymxsqList) { if (jyxxsq.getDdh().equals(vo.getDdh())) { //mx = getMx(vo); vo.setSqlsh(jyxxsq.getSqlsh()); //mxList.add(mx); } } if(null != jymxsqClList && !jymxsqClList.isEmpty()){ for (JymxsqCl vo : jymxsqClList) { if (jyxxsq.getDdh().equals(vo.getDdh())) { vo.setSqlsh(jyxxsq.getSqlsh()); } } } if (null != jyzfmxList && !jyzfmxList.isEmpty()) { for (Jyzfmx vo : jyzfmxList) { if (jyxxsq.getDdh().equals(vo.getDdh())) { vo.setSqlsh(jyxxsq.getSqlsh()); } } } } //jymxsqservice.save(jymxsqList); jymxsqservice.addJymxsqBatch(jymxsqList); if(null != jymxsqClList && !jymxsqClList.isEmpty()){ //jymxsqClService.save(jymxsqClList); System.out.println("jymxsqClList开始保存时间"+new Date()); jymxsqClService.addJymxsqClBatch(jymxsqClList); System.out.println("jymxsqClList结束保存时间"+new Date()); } if(null != jyzfmxList && !jyzfmxList.isEmpty()){ //jyzfmxService.save(jyzfmxList); jyzfmxService.addJyzfmxBatch(jyzfmxList); } } private Jymxsq getMx(JymxsqVo vo) { Jymxsq mx = new Jymxsq(vo.getSpmxxh(), vo.getFphxz(), vo.getSpdm(), vo.getSpmc(), vo.getSpggxh(), vo.getSpdw(), vo.getSps(), vo.getSpdj(), vo.getSpje(), vo.getSpsl(), vo.getSpse(), vo.getJshj(),vo.getHzkpxh(), vo.getLrsj(), vo.getLrry(), vo.getXgsj(), vo.getXgry(), vo.getGsdm(), vo.getXfid(), vo.getSkpid(),vo.getYxbz(),vo.getKkjje(),vo.getYkjje()); return mx; } public List<JyxxsqVO> findBykplscxPage(Map params) { // TODO Auto-generated method stub return jyxxsqMapper.findBykplscxPage(params); } public Integer findBykplscxtotal(Map params){ return jyxxsqMapper.findBykplscxtotal(params); } public Skp findskpExistByXfid(Map tt) { return jyxxsqMapper.findskpExistByXfid(tt); } public Jyxxsq findOneByJylsh(Map jyxxsqMap) { return jyxxsqMapper.findOneByJylsh(jyxxsqMap); } }
UTF-8
Java
8,320
java
JyxxsqService.java
Java
[ { "context": "类自动生成\n * <p>\n * Wed Jan 04 13:33:08 CST 2017\n *\n * @ZhangBing\n */ \n@Service\npublic class JyxxsqService", "end": 622, "score": 0.9934786558151245, "start": 622, "tag": "USERNAME", "value": "" }, { "context": "动生成\n * <p>\n * Wed Jan 04 13:33:08 CST 2017\n *\n * @Z...
null
[]
package com.rjxx.taxeasy.dal; import com.rjxx.comm.mybatis.Pagination; import com.rjxx.taxeasy.dao.bo.*; import com.rjxx.taxeasy.dao.orm.JyxxsqJpaDao; import com.rjxx.taxeasy.dao.orm.JyxxsqMapper; import com.rjxx.taxeasy.dao.vo.JymxsqVo; import com.rjxx.taxeasy.dao.vo.JyxxsqVO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; /** * 由GenJavaCode类自动生成 * <p> * Wed Jan 04 13:33:08 CST 2017 * * @ZhangBing */ @Service public class JyxxsqService { @Autowired private JyxxsqJpaDao jyxxsqJpaDao; @Autowired private JyxxsqMapper jyxxsqMapper; @Autowired private JymxsqService jymxsqservice; @Autowired private JymxsqClService jymxsqClService; @Autowired private JyzfmxService jyzfmxService; public Jyxxsq findOne(int id) { return jyxxsqJpaDao.findOne(id); } public void save(Jyxxsq jyxxsq) { jyxxsqJpaDao.save(jyxxsq); } public void save(List<Jyxxsq> jyxxsqList) { jyxxsqJpaDao.save(jyxxsqList); } public Jyxxsq findOneByParams(Map params) { return jyxxsqMapper.findOneByParams(params); } public Jyxxsq findOneByTqmAndJshj(Map params) { return jyxxsqMapper.findOneByTqmAndJshj(params); } public List<Jyxxsq> findAllByTqms(Map params) { return jyxxsqMapper.findAllByTqms(params); } public List<Jyxxsq> findAllByJylshs(Map params) { return jyxxsqMapper.findAllByJylshs(params); } public Jyxxsq findSjlyAndOpenidByMap(Map params) { return jyxxsqMapper.findSjlyAndOpenidByMap(params); } public List<Jyxxsq> findAllByDdhs(Map params) { return jyxxsqMapper.findAllByDdhs(params); } public List<JyxxsqVO> findByPage(Pagination pagination) { return jyxxsqMapper.findByPage(pagination); } public List<Jyxxsq> findByPage1(Pagination pagination) { return jyxxsqMapper.findByPage1(pagination); } public List<Jyxxsq> findByMapParams(Map params) { return jyxxsqMapper.findByMapParams(params); } public Xf findXfExistByKpd(Map params) { return jyxxsqMapper.findXfExistByKpd(params); } public Xf findXfExistByXfsh(Map params) { return jyxxsqMapper.findXfExistByXfsh(params); } public void saveJyxxsq(Jyxxsq jyxxsq){ jyxxsqMapper.saveJyxxsq(jyxxsq); } public void addJyxxsqBatch(List<Jyxxsq> Jyxxsqs){ jyxxsqMapper.addJyxxsqBatch(Jyxxsqs); } public List<JyxxsqVO> findYscByPage(Pagination pagination){ return jyxxsqMapper.findYscByPage(pagination); } public void updateGfxx(Map params){ jyxxsqMapper.updateGfxx(params); } public List<JyxxsqVO> findByPage2(Map params) { return jyxxsqMapper.findByPage2(params); } public Integer findtotal(Map params) { return jyxxsqMapper.findtotal(params); } /** * 删除交易流水,包括明细 * * @param sqlshList */ @Transactional public void delBySqlshList(List<Integer> sqlshList) { Iterable<Jyxxsq> jylsIterable = jyxxsqJpaDao.findAll(sqlshList); jyxxsqJpaDao.delete(jylsIterable); List<Jymxsq> jymxsqList = jymxsqservice.findBySqlshList(sqlshList); jymxsqservice.delete(jymxsqList); } /** * 删除交易流水,包括明细以及处理明细 * * @param sqlshList */ @Transactional public void delBySqlshList2(List<Integer> sqlshList) { Iterable<Jyxxsq> jylsIterable = jyxxsqJpaDao.findAll(sqlshList); jyxxsqJpaDao.delete(jylsIterable); List<Jymxsq> jymxsqList = jymxsqservice.findBySqlshList(sqlshList); List<JymxsqCl> jymxsqCLList = jymxsqClService.findBySqlshList(sqlshList); jymxsqservice.delete(jymxsqList); jymxsqClService.delete(jymxsqCLList); } /** * 更新jyxxsq状态 * * @param sqlshList * @param clztdm */ public void updateJyxxsqZtzt(List<Integer> sqlshList, String ztbz) { List<Jyxxsq> jylsIterable = (List<Jyxxsq>) jyxxsqJpaDao.findAll(sqlshList); for (Jyxxsq jyxxsq : jylsIterable) { jyxxsq.setZtbz(ztbz); jyxxsq.setXgsj(new Date()); } save(jylsIterable); } /** * 保存交易信息申请 * * @param jyxxsq * @param jymxsqList */ @Transactional public Integer saveJyxxsq(Jyxxsq jyxxsq, List<Jymxsq> jymxsqList) { save(jyxxsq); int sqlsh = jyxxsq.getSqlsh(); for (Jymxsq Jymxsq : jymxsqList) { Jymxsq.setSqlsh(sqlsh); } jymxsqservice.save(jymxsqList); return sqlsh; } /** * 保存交易信息申请 * * @param jyxxsq * @param jymxsqList */ @Transactional public Integer saveJyxxsq(Jyxxsq jyxxsq, List<Jymxsq> jymxsqList,List<JymxsqCl> jymxsqClList,List<Jyzfmx> jyzfmxList) { save(jyxxsq); int sqlsh = jyxxsq.getSqlsh(); for (Jymxsq Jymxsq : jymxsqList) { Jymxsq.setSqlsh(sqlsh); } if(null != jymxsqClList && !jymxsqClList.isEmpty()){ for (JymxsqCl jymxsqCl : jymxsqClList) { jymxsqCl.setSqlsh(sqlsh); } jymxsqClService.save(jymxsqClList); } if(null != jyzfmxList && !jyzfmxList.isEmpty()){ for (Jyzfmx jyzfmx : jyzfmxList) { jyzfmx.setSqlsh(sqlsh); } jyzfmxService.save(jyzfmxList); } jymxsqservice.save(jymxsqList); return sqlsh; } /** * 交易信息申请与明细一对一 * * @param jyxxsqList * @param jymxsqList */ @Transactional public void saveAll(List<Jyxxsq> jyxxsqList, List<JymxsqVo> jymxsqList) { jyxxsqJpaDao.save(jyxxsqList); List<Jymxsq> mxList = new ArrayList<>(); Jymxsq mx = null; for (Jyxxsq jyxxsq : jyxxsqList) { for (JymxsqVo vo : jymxsqList) { if (jyxxsq.getDdh().equals(vo.getDdh())) { mx = getMx(vo); mx.setSqlsh(jyxxsq.getSqlsh()); mxList.add(mx); } } } jymxsqservice.save(mxList); } /** * 交易信息申请与明细一对一 * * @param jyxxsqList * @param jymxsqList * @param jymxsqClList * @param jyzfmxList */ @Transactional public void saveAll(List<Jyxxsq> jyxxsqList, List<Jymxsq> jymxsqList,List<JymxsqCl> jymxsqClList,List<Jyzfmx> jyzfmxList) throws Exception{ //jyxxsqJpaDao.save(jyxxsqList); addJyxxsqBatch(jyxxsqList); List<Jymxsq> mxList = new ArrayList<>(); Jymxsq mx = null; for (Jyxxsq jyxxsq : jyxxsqList) { for (Jymxsq vo : jymxsqList) { if (jyxxsq.getDdh().equals(vo.getDdh())) { //mx = getMx(vo); vo.setSqlsh(jyxxsq.getSqlsh()); //mxList.add(mx); } } if(null != jymxsqClList && !jymxsqClList.isEmpty()){ for (JymxsqCl vo : jymxsqClList) { if (jyxxsq.getDdh().equals(vo.getDdh())) { vo.setSqlsh(jyxxsq.getSqlsh()); } } } if (null != jyzfmxList && !jyzfmxList.isEmpty()) { for (Jyzfmx vo : jyzfmxList) { if (jyxxsq.getDdh().equals(vo.getDdh())) { vo.setSqlsh(jyxxsq.getSqlsh()); } } } } //jymxsqservice.save(jymxsqList); jymxsqservice.addJymxsqBatch(jymxsqList); if(null != jymxsqClList && !jymxsqClList.isEmpty()){ //jymxsqClService.save(jymxsqClList); System.out.println("jymxsqClList开始保存时间"+new Date()); jymxsqClService.addJymxsqClBatch(jymxsqClList); System.out.println("jymxsqClList结束保存时间"+new Date()); } if(null != jyzfmxList && !jyzfmxList.isEmpty()){ //jyzfmxService.save(jyzfmxList); jyzfmxService.addJyzfmxBatch(jyzfmxList); } } private Jymxsq getMx(JymxsqVo vo) { Jymxsq mx = new Jymxsq(vo.getSpmxxh(), vo.getFphxz(), vo.getSpdm(), vo.getSpmc(), vo.getSpggxh(), vo.getSpdw(), vo.getSps(), vo.getSpdj(), vo.getSpje(), vo.getSpsl(), vo.getSpse(), vo.getJshj(),vo.getHzkpxh(), vo.getLrsj(), vo.getLrry(), vo.getXgsj(), vo.getXgry(), vo.getGsdm(), vo.getXfid(), vo.getSkpid(),vo.getYxbz(),vo.getKkjje(),vo.getYkjje()); return mx; } public List<JyxxsqVO> findBykplscxPage(Map params) { // TODO Auto-generated method stub return jyxxsqMapper.findBykplscxPage(params); } public Integer findBykplscxtotal(Map params){ return jyxxsqMapper.findBykplscxtotal(params); } public Skp findskpExistByXfid(Map tt) { return jyxxsqMapper.findskpExistByXfid(tt); } public Jyxxsq findOneByJylsh(Map jyxxsqMap) { return jyxxsqMapper.findOneByJylsh(jyxxsqMap); } }
8,320
0.694103
0.692015
320
24.434376
24.4643
185
false
false
0
0
0
0
0
0
1.75
false
false
13
28b2b0b7bb069f94392f687bc26decddc3ace8b0
28,260,884,839,242
d81bb572943defe220f2765238164a4fcf4c97ae
/GerritDownloader/src/main/java/com/holmsted/gerrit/downloaders/http/HttpProjectLister.java
079710134d31dbc409858dfa5df39cef9b113f67
[ "MIT" ]
permissive
Ziver/gerritstats
https://github.com/Ziver/gerritstats
f20db54150a6e98931de62979f568f773f7b78e5
19e3bb327256386c3a0ba9b3ec877a31bd3bee11
refs/heads/master
2023-01-21T23:34:22.849000
2020-11-30T15:01:07
2020-11-30T15:01:07
261,197,143
0
0
MIT
true
2020-05-04T14:04:52
2020-05-04T14:04:51
2020-04-17T17:49:17
2020-05-02T02:54:13
2,560
0
0
0
null
false
false
package com.holmsted.gerrit.downloaders.http; import com.holmsted.gerrit.GerritServer; import com.holmsted.gerrit.downloaders.GerritProjectLister; import org.json.JSONObject; import javax.annotation.Nonnull; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Creates a listing of all Gerrit projects on the given server. */ public class HttpProjectLister extends GerritProjectLister { public HttpProjectLister(@Nonnull GerritServer gerritServer) { super(gerritServer); } @Nonnull public List<String> getProjectListing() { ArrayList<String> output = new ArrayList<>(); try { JSONObject json = HttpUtils.createJSONGetRequest(getGerritServer().getServerAddress() + "/projects/"); output.addAll(json.keySet()); } catch (IOException e) { e.printStackTrace(); } return output; } }
UTF-8
Java
951
java
HttpProjectLister.java
Java
[]
null
[]
package com.holmsted.gerrit.downloaders.http; import com.holmsted.gerrit.GerritServer; import com.holmsted.gerrit.downloaders.GerritProjectLister; import org.json.JSONObject; import javax.annotation.Nonnull; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Creates a listing of all Gerrit projects on the given server. */ public class HttpProjectLister extends GerritProjectLister { public HttpProjectLister(@Nonnull GerritServer gerritServer) { super(gerritServer); } @Nonnull public List<String> getProjectListing() { ArrayList<String> output = new ArrayList<>(); try { JSONObject json = HttpUtils.createJSONGetRequest(getGerritServer().getServerAddress() + "/projects/"); output.addAll(json.keySet()); } catch (IOException e) { e.printStackTrace(); } return output; } }
951
0.701367
0.701367
34
26.970589
25.619944
114
false
false
0
0
0
0
0
0
0.441176
false
false
13
64ce62624ae6ee3f69ce4926f3714a7cd7a46aa4
26,499,948,237,940
2fb742a7dfc35842d3a2cc32e46e8cf65617aa99
/app/src/main/java/com/andrewpbrown/weatherapp/CustomUtils.java
f2df3610d742da21aeddbf4aced39a2490e6a89d
[]
no_license
APBrown/weatherApp
https://github.com/APBrown/weatherApp
9d71bc28769a12e721a2c96cdaea514a214300ba
37c01a154d37b6af2bbbce1c6943e435ce30f63a
refs/heads/master
2021-05-08T02:37:48.196000
2017-10-23T23:28:51
2017-10-23T23:28:51
108,030,372
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.andrewpbrown.weatherapp; import android.content.Context; import android.content.res.Resources; import android.graphics.drawable.Drawable; class CustomUtils { static Drawable getImageResource(Context context, String iconName) { Resources res = context.getResources(); int resID = res.getIdentifier(iconName , "drawable", context.getPackageName()); return context.getDrawable(resID); } static double convertWeatherToMph(double speed) { return speed * 2.23694; } }
UTF-8
Java
526
java
CustomUtils.java
Java
[ { "context": "package com.andrewpbrown.weatherapp;\n\nimport android.content.Context;\nimpo", "end": 24, "score": 0.9804338216781616, "start": 12, "tag": "USERNAME", "value": "andrewpbrown" } ]
null
[]
package com.andrewpbrown.weatherapp; import android.content.Context; import android.content.res.Resources; import android.graphics.drawable.Drawable; class CustomUtils { static Drawable getImageResource(Context context, String iconName) { Resources res = context.getResources(); int resID = res.getIdentifier(iconName , "drawable", context.getPackageName()); return context.getDrawable(resID); } static double convertWeatherToMph(double speed) { return speed * 2.23694; } }
526
0.726236
0.714829
18
28.222221
25.778017
87
false
false
0
0
0
0
0
0
0.611111
false
false
13
165b73e49791e7191ed7c473c52a485062051630
19,189,913,899,121
42e567e0cdd184557b2fc8dab2c19746d99648c2
/src/com/sopings/activity/Operation.java
37b4f4178cfede08f7522324a4a5e573c8a75bae
[]
no_license
seathiefwang/huiguanjia
https://github.com/seathiefwang/huiguanjia
e84727a93b41f82d39ebd7a482179f1f96e328f2
2dc8e843c1bd09493855188d3074d25a1abf3e74
refs/heads/master
2016-06-04T11:32:24.430000
2015-12-26T10:07:43
2015-12-26T10:07:43
44,040,070
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.sopings.activity; import com.sopings.huiguanjia.R; import android.app.Activity; import android.os.Bundle; public class Operation extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { // TODO 自动生成的方法存根 super.onCreate(savedInstanceState); setContentView(R.layout.smart_operation); } }
GB18030
Java
355
java
Operation.java
Java
[]
null
[]
package com.sopings.activity; import com.sopings.huiguanjia.R; import android.app.Activity; import android.os.Bundle; public class Operation extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { // TODO 自动生成的方法存根 super.onCreate(savedInstanceState); setContentView(R.layout.smart_operation); } }
355
0.783383
0.783383
17
18.82353
17.862993
53
false
false
0
0
0
0
0
0
0.882353
false
false
13
2c316725507629acb0f33272b47caae9e13eb65a
29,222,957,489,356
a35260a439b91dc5df836bd41e70e6ceb2319aef
/misc/src/main/java/com/puresoltechnologies/commons/misc/hash/HashCodeGenerator.java
3323c85e87ba7a74abb4ec3f7a4b79197720b315
[ "Apache-2.0" ]
permissive
PureSolTechnologies/commons
https://github.com/PureSolTechnologies/commons
0b5eafec32b9e2a40783e9c32e79505e0a1dd7ed
b6473b2e04dd650b7766223732d2fd1393246759
refs/heads/master
2023-03-16T09:51:32.140000
2019-08-05T19:32:18
2019-08-05T19:32:18
27,091,242
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.puresoltechnologies.commons.misc.hash; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.Provider; import java.security.Security; import java.util.HashSet; import java.util.Set; import com.puresoltechnologies.commons.types.StringUtils; public class HashCodeGenerator { public static String[] getServiceTypes() { Set<String> result = new HashSet<String>(); for (Provider provider : Security.getProviders()) { for (Object providerKey : provider.keySet()) { String key = providerKey.toString(); key = key.split(" ")[0]; if (key.startsWith("Alg.Alias.")) { key = key.substring(10); } int ix = key.indexOf('.'); result.add(key.substring(0, ix)); } } return result.toArray(new String[result.size()]); } public static String[] getCryptoImpls(String serviceType) { Set<String> result = new HashSet<String>(); for (Provider provider : Security.getProviders()) { for (Object providerKey : provider.keySet()) { String key = providerKey.toString(); key = key.split(" ")[0]; if (key.startsWith(serviceType + ".")) { result.add(key.substring(serviceType.length() + 1)); } else if (key.startsWith("Alg.Alias." + serviceType + ".")) { result.add(key.substring(serviceType.length() + 11)); } } } return result.toArray(new String[result.size()]); } public static String[] getCryptoImpls() { Set<String> result = new HashSet<String>(); for (Provider provider : Security.getProviders()) { for (Object providerKey : provider.keySet()) { String key = providerKey.toString(); key = key.split(" ")[0]; result.add(key); } } return result.toArray(new String[result.size()]); } public static String get(HashAlgorithm algorithm, String line) { try { /* Calculation */ MessageDigest digest = MessageDigest.getInstance(algorithm .getAlgorithmName()); digest.reset(); digest.update(line.getBytes(Charset.defaultCharset())); byte[] result = digest.digest(); return StringUtils.convertByteArrayToString(result); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Something strange is going on in " + algorithm + "module! Is there no " + algorithm + "supported!?", e); } } public static String get(HashAlgorithm algorithm, ByteBuffer bytes) { try { /* Calculation */ MessageDigest digest = MessageDigest.getInstance(algorithm .getAlgorithmName()); digest.reset(); digest.update(bytes); byte[] result = digest.digest(); return StringUtils.convertByteArrayToString(result); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Something strange is going on in " + algorithm + "module! Is there no " + algorithm + "supported!?", e); } } public static String getMD5(String line) { return get(HashAlgorithm.MD5, line); } public static String getSHA(String line) { return get(HashAlgorithm.SHA1, line); } public static String getSHA256(String line) { return get(HashAlgorithm.SHA256, line); } public static String getSHA384(String line) { return get(HashAlgorithm.SHA384, line); } public static String getSHA512(String line) { return get(HashAlgorithm.SHA512, line); } }
UTF-8
Java
3,330
java
HashCodeGenerator.java
Java
[]
null
[]
package com.puresoltechnologies.commons.misc.hash; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.Provider; import java.security.Security; import java.util.HashSet; import java.util.Set; import com.puresoltechnologies.commons.types.StringUtils; public class HashCodeGenerator { public static String[] getServiceTypes() { Set<String> result = new HashSet<String>(); for (Provider provider : Security.getProviders()) { for (Object providerKey : provider.keySet()) { String key = providerKey.toString(); key = key.split(" ")[0]; if (key.startsWith("Alg.Alias.")) { key = key.substring(10); } int ix = key.indexOf('.'); result.add(key.substring(0, ix)); } } return result.toArray(new String[result.size()]); } public static String[] getCryptoImpls(String serviceType) { Set<String> result = new HashSet<String>(); for (Provider provider : Security.getProviders()) { for (Object providerKey : provider.keySet()) { String key = providerKey.toString(); key = key.split(" ")[0]; if (key.startsWith(serviceType + ".")) { result.add(key.substring(serviceType.length() + 1)); } else if (key.startsWith("Alg.Alias." + serviceType + ".")) { result.add(key.substring(serviceType.length() + 11)); } } } return result.toArray(new String[result.size()]); } public static String[] getCryptoImpls() { Set<String> result = new HashSet<String>(); for (Provider provider : Security.getProviders()) { for (Object providerKey : provider.keySet()) { String key = providerKey.toString(); key = key.split(" ")[0]; result.add(key); } } return result.toArray(new String[result.size()]); } public static String get(HashAlgorithm algorithm, String line) { try { /* Calculation */ MessageDigest digest = MessageDigest.getInstance(algorithm .getAlgorithmName()); digest.reset(); digest.update(line.getBytes(Charset.defaultCharset())); byte[] result = digest.digest(); return StringUtils.convertByteArrayToString(result); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Something strange is going on in " + algorithm + "module! Is there no " + algorithm + "supported!?", e); } } public static String get(HashAlgorithm algorithm, ByteBuffer bytes) { try { /* Calculation */ MessageDigest digest = MessageDigest.getInstance(algorithm .getAlgorithmName()); digest.reset(); digest.update(bytes); byte[] result = digest.digest(); return StringUtils.convertByteArrayToString(result); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Something strange is going on in " + algorithm + "module! Is there no " + algorithm + "supported!?", e); } } public static String getMD5(String line) { return get(HashAlgorithm.MD5, line); } public static String getSHA(String line) { return get(HashAlgorithm.SHA1, line); } public static String getSHA256(String line) { return get(HashAlgorithm.SHA256, line); } public static String getSHA384(String line) { return get(HashAlgorithm.SHA384, line); } public static String getSHA512(String line) { return get(HashAlgorithm.SHA512, line); } }
3,330
0.693393
0.684384
113
28.469027
21.782948
70
false
false
0
0
0
0
0
0
2.495575
false
false
13
2466611790e66ec3fba30dd6e9d8c57f054042b7
515,396,116,730
6ac30e55cfcb5e02a8eb190fa8ac4abe8125a188
/src/cn/chenjaly/servletlearn/TestJDBC.java
87f19bb1f5a68890767a0201c4931ca98596cbeb
[]
no_license
CodeChenL/cn.chenjaly.java_web
https://github.com/CodeChenL/cn.chenjaly.java_web
deae09b5023e0293959adb5cda009de6f2c28b23
029fad78caaede51a5cf338c21ef19d154003424
refs/heads/master
2022-12-31T02:04:39.288000
2020-10-25T09:54:13
2020-10-25T09:54:13
298,667,994
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.chenjaly.servletlearn; import java.sql.*; public class TestJDBC { public static void main(String[] args) throws Exception { Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/class3?characterEncoding=utf-8&useSSL=false","root","1234"); if (con!=null){ System.out.println(con+"数据库连接成功"); }else { System.out.println("数据库连接失败"); } Statement statement = con.createStatement(); ResultSet resultSet = statement.executeQuery("select * from user "); System.out.println("从数据库取出信息"); while (resultSet.next()){ System.out.print(resultSet.getInt("id")+"\t"); System.out.print(resultSet.getString("username")+"\t"); System.out.print(resultSet.getString("password")+"\t"); } resultSet.close(); statement.close(); con.close(); } }
UTF-8
Java
1,008
java
TestJDBC.java
Java
[]
null
[]
package cn.chenjaly.servletlearn; import java.sql.*; public class TestJDBC { public static void main(String[] args) throws Exception { Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/class3?characterEncoding=utf-8&useSSL=false","root","1234"); if (con!=null){ System.out.println(con+"数据库连接成功"); }else { System.out.println("数据库连接失败"); } Statement statement = con.createStatement(); ResultSet resultSet = statement.executeQuery("select * from user "); System.out.println("从数据库取出信息"); while (resultSet.next()){ System.out.print(resultSet.getInt("id")+"\t"); System.out.print(resultSet.getString("username")+"\t"); System.out.print(resultSet.getString("password")+"\t"); } resultSet.close(); statement.close(); con.close(); } }
1,008
0.607884
0.59751
26
36.076923
30.509674
142
false
false
0
0
0
0
0
0
0.653846
false
false
13
65896390a77a784623508a356e47b6e97353102b
12,558,484,442,025
9f81e8df68328d8444d1d90431aa558ac662103d
/src/clase21Mesa/ParaEnvio.java
c18c0ec30d26416a97a7f2597136b90c2bfefb48
[]
no_license
dsromeror/POO---Digital-House---Certified-Tech-Developer---Daniel-Romero
https://github.com/dsromeror/POO---Digital-House---Certified-Tech-Developer---Daniel-Romero
be73475685d4b56c741503b4192c6f4c0232e6c5
5bbaaa0d9f7f8448c336ccf7622995e0cafdd015
refs/heads/main
2023-06-29T21:33:10.031000
2021-07-29T23:10:18
2021-07-29T23:10:18
387,817,635
0
3
null
null
null
null
null
null
null
null
null
null
null
null
null
package clase21Mesa; public class ParaEnvio implements ReparacionState{ private Reparacion r; public ParaEnvio(Reparacion r) { this.r = r; System.out.println("Para envio"); } @Override public void valorPresupuesto(double v) { System.out.println("No disponible"); } @Override public void sumaRepuesto(double v) { System.out.println("No disponible"); } @Override public void cambiarDireccion(String v) { r.getReparacionState().cambiarDireccion(v); } @Override public void pasarSigPaso() { r.setReparacionState(new Finalizando(r)); } }
UTF-8
Java
647
java
ParaEnvio.java
Java
[]
null
[]
package clase21Mesa; public class ParaEnvio implements ReparacionState{ private Reparacion r; public ParaEnvio(Reparacion r) { this.r = r; System.out.println("Para envio"); } @Override public void valorPresupuesto(double v) { System.out.println("No disponible"); } @Override public void sumaRepuesto(double v) { System.out.println("No disponible"); } @Override public void cambiarDireccion(String v) { r.getReparacionState().cambiarDireccion(v); } @Override public void pasarSigPaso() { r.setReparacionState(new Finalizando(r)); } }
647
0.638331
0.63524
30
20.566668
18.570017
51
false
false
0
0
0
0
0
0
0.266667
false
false
13
055717cb13c0059890fee0f8a1e0405c27665c9b
32,658,931,340,031
4b128df9281179873ca100afe527d8907d61c918
/Cours TD et TP Langage java/TP-TD 3 (Corrigé)/Exercice 2/GestionVehicules.java
f458c3b602dc11406f05857191c7e2bdd6d82340
[]
no_license
walidabdellaziz/Langage-Java-Cours-TD-ET-TP
https://github.com/walidabdellaziz/Langage-Java-Cours-TD-ET-TP
26471a5ace3bfeb2958eb18f3dcc88d02c92cb4f
91de60f1ec3bc8577a7503a811a5d429da1065ed
refs/heads/master
2021-03-29T16:06:24.412000
2020-05-27T18:51:57
2020-05-27T18:51:57
247,966,360
9
3
null
null
null
null
null
null
null
null
null
null
null
null
null
package GestionVehicules; class GestionVehicules { private static int ANNEE_ACTUELLE = 2012; public static void main(String[] args) { Vehicule[] vehicules = new Vehicule [5]; vehicules[0] = new Voiture("Peugeot", 2005, 147325.79, 2.5, 5, 180.0, 12000); vehicules[1] = new Voiture("Porsche", 1999, 250000.00, 6.5, 2, 280.0, 81320); vehicules[2] = new Voiture("Fiat", 2001, 7327.30, 1.6, 3, 65.0, 3000); vehicules[3] = new Avion("Cessna", 1982, 1230673.90, "HELICES", 250); vehicules[4] = new Avion("Nain Connu", 1993, 4321098.00, "REACTION", 1300); for (int i = 0; i < vehicules.length; i++) { vehicules[i].calculePrix(ANNEE_ACTUELLE); vehicules[i].affiche(); } } }
UTF-8
Java
719
java
GestionVehicules.java
Java
[ { "context": "6, 3, 65.0, 3000);\r\n\r\n\t\tvehicules[3] = new Avion(\"Cessna\", 1982, 1230673.90, \"HELICES\", 250);\r\n\t\tvehicules", "end": 465, "score": 0.9928576350212097, "start": 459, "tag": "NAME", "value": "Cessna" }, { "context": "les[3] = new Avion(\"Cessna\", 1982, 12306...
null
[]
package GestionVehicules; class GestionVehicules { private static int ANNEE_ACTUELLE = 2012; public static void main(String[] args) { Vehicule[] vehicules = new Vehicule [5]; vehicules[0] = new Voiture("Peugeot", 2005, 147325.79, 2.5, 5, 180.0, 12000); vehicules[1] = new Voiture("Porsche", 1999, 250000.00, 6.5, 2, 280.0, 81320); vehicules[2] = new Voiture("Fiat", 2001, 7327.30, 1.6, 3, 65.0, 3000); vehicules[3] = new Avion("Cessna", 1982, 1230673.90, "HELICES", 250); vehicules[4] = new Avion("<NAME>", 1993, 4321098.00, "REACTION", 1300); for (int i = 0; i < vehicules.length; i++) { vehicules[i].calculePrix(ANNEE_ACTUELLE); vehicules[i].affiche(); } } }
715
0.635605
0.479833
22
30.681818
29.448547
79
false
false
0
0
0
0
0
0
2.909091
false
false
13
91c1467005c025e103960f56ecbc64abdd8faab7
12,309,376,284,370
ad7ba5eafef808d14c69615e1b64e3daaa18baea
/repoFP/FactoryProject/src/com/factoryproject/model/Message.java
e3236e86ec955b0c6bdf29aecb08f47abbcb53f9
[]
no_license
KoanJan/FactoryProject
https://github.com/KoanJan/FactoryProject
3c8dce26bab691106df3c0b94b51a9b0e34894c5
3d32ab51da2a5501ef6360b5e53fae5b7a681eda
refs/heads/master
2021-01-16T18:45:34.191000
2014-08-05T11:32:37
2014-08-05T11:32:37
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.factoryproject.model; // Generated 2014-4-8 20:35:51 by Hibernate Tools 3.2.0.b9 import java.sql.Timestamp; import java.util.Date; /** * Represents a single playable track in the music * database. @author Jim Elliott (with help from Hibernate) */ public class Message implements java.io.Serializable { private int id; private String content; /** * When the message was created */ private Timestamp dateAdded; /** * Messages by this user */ private User speaker; /** * The Messages replied to */ private Message replyingMessageID; public Message() { } public Message(String content, User speaker) { this.content = content; this.speaker = speaker; } public Message(String content, Timestamp dateAdded, User speaker, Message replyingMessageID) { this.content = content; this.dateAdded = dateAdded; this.speaker = speaker; this.replyingMessageID = replyingMessageID; } public int getId() { return this.id; } protected void setId(int id) { this.id = id; } public String getContent() { return this.content; } public void setContent(String content) { this.content = content; } /** * * When the message was created */ public Timestamp getDateAdded() { return this.dateAdded; } public void setDateAdded(Timestamp dateAdded) { this.dateAdded = dateAdded; } /** * * Messages by this user */ public User getSpeaker() { return this.speaker; } public void setSpeaker(User speaker) { this.speaker = speaker; } /** * * the Messages replied to */ public Message getReplyingMessageID() { return this.replyingMessageID; } public void setReplyingMessageID(Message replyingMessageID) { this.replyingMessageID = replyingMessageID; } @Override public String toString() { return "Message [id=" + id + ", content=" + content + ", dateAdded=" + dateAdded + ", speaker=" + speaker + ", replyingMessageID=" + replyingMessageID + "]"; } }
UTF-8
Java
2,278
java
Message.java
Java
[ { "context": "layable track in the music\n * \t\t\tdatabase. @author Jim Elliott (with help from Hibernate)\n */\npublic class Messa", "end": 236, "score": 0.99977707862854, "start": 225, "tag": "NAME", "value": "Jim Elliott" } ]
null
[]
package com.factoryproject.model; // Generated 2014-4-8 20:35:51 by Hibernate Tools 3.2.0.b9 import java.sql.Timestamp; import java.util.Date; /** * Represents a single playable track in the music * database. @author <NAME> (with help from Hibernate) */ public class Message implements java.io.Serializable { private int id; private String content; /** * When the message was created */ private Timestamp dateAdded; /** * Messages by this user */ private User speaker; /** * The Messages replied to */ private Message replyingMessageID; public Message() { } public Message(String content, User speaker) { this.content = content; this.speaker = speaker; } public Message(String content, Timestamp dateAdded, User speaker, Message replyingMessageID) { this.content = content; this.dateAdded = dateAdded; this.speaker = speaker; this.replyingMessageID = replyingMessageID; } public int getId() { return this.id; } protected void setId(int id) { this.id = id; } public String getContent() { return this.content; } public void setContent(String content) { this.content = content; } /** * * When the message was created */ public Timestamp getDateAdded() { return this.dateAdded; } public void setDateAdded(Timestamp dateAdded) { this.dateAdded = dateAdded; } /** * * Messages by this user */ public User getSpeaker() { return this.speaker; } public void setSpeaker(User speaker) { this.speaker = speaker; } /** * * the Messages replied to */ public Message getReplyingMessageID() { return this.replyingMessageID; } public void setReplyingMessageID(Message replyingMessageID) { this.replyingMessageID = replyingMessageID; } @Override public String toString() { return "Message [id=" + id + ", content=" + content + ", dateAdded=" + dateAdded + ", speaker=" + speaker + ", replyingMessageID=" + replyingMessageID + "]"; } }
2,273
0.593064
0.58604
103
21.097088
20.064709
98
false
false
0
0
0
0
0
0
0.485437
false
false
13
0792faed0716ca519b328816fd7fda4327d36276
14,714,557,956,447
048e4e6bcf5473244809d11aba91efa57e00b361
/carpark-dao/src/main/java/cz/muni/fi/pa165/carpark/entity/User.java
a14ea559d7589d85d941ccead75834247a6d2dd6
[]
no_license
Gorgion/CarPark
https://github.com/Gorgion/CarPark
5dab242fc9fda3ad91a12b732967cd6c9a9bdd4d
ccce6e004b53bc7378c1bc7b0404985b65e4a71a
refs/heads/master
2020-05-18T04:18:56.528000
2015-01-23T19:19:28
2015-01-23T19:19:28
38,200,788
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package cz.muni.fi.pa165.carpark.entity; //import cz.muni.fi.pa165.carpark.dto.UserDto; import java.io.Serializable; import java.util.Objects; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.Table; /** * Entity representing a user. * * @author Tomáš Vašíček */ @Entity @Table(name = "users") public class User implements Serializable { @Id @GeneratedValue private Long id; @Column(nullable = false) private String firstName; @Column(nullable = false) private String lastName; @Column(nullable = false, unique = true) private String birthNumber; private String address; @ManyToOne private Office office; @Override public String toString() { return "User{" + "Id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", birthNumber=" + birthNumber + ", address=" + address + '}'; } @Override public int hashCode() { int hash = 5; hash = 29 * hash + Objects.hashCode(this.id); return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final User other = (User) obj; if (!Objects.equals(this.id, other.id)) { return false; } return true; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getBirthNumber() { return birthNumber; } public void setBirthNumber(String birthNumber) { this.birthNumber = birthNumber; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } /** * @return the office */ public Office getOffice() { return office; } /** * @param office the office to set */ public void setOffice(Office office) { this.office = office; } }
UTF-8
Java
2,769
java
User.java
Java
[ { "context": "\n/**\n * Entity representing a user.\n * \n * @author Tomáš Vašíček\n */\n\n@Entity\n@Table(name = \"users\")\npublic class ", "end": 600, "score": 0.9998748898506165, "start": 587, "tag": "NAME", "value": "Tomáš Vašíček" }, { "context": " return \"User{\" + \"Id=\"...
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package cz.muni.fi.pa165.carpark.entity; //import cz.muni.fi.pa165.carpark.dto.UserDto; import java.io.Serializable; import java.util.Objects; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.Table; /** * Entity representing a user. * * @author <NAME> */ @Entity @Table(name = "users") public class User implements Serializable { @Id @GeneratedValue private Long id; @Column(nullable = false) private String firstName; @Column(nullable = false) private String lastName; @Column(nullable = false, unique = true) private String birthNumber; private String address; @ManyToOne private Office office; @Override public String toString() { return "User{" + "Id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", birthNumber=" + birthNumber + ", address=" + address + '}'; } @Override public int hashCode() { int hash = 5; hash = 29 * hash + Objects.hashCode(this.id); return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final User other = (User) obj; if (!Objects.equals(this.id, other.id)) { return false; } return true; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getBirthNumber() { return birthNumber; } public void setBirthNumber(String birthNumber) { this.birthNumber = birthNumber; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } /** * @return the office */ public Office getOffice() { return office; } /** * @param office the office to set */ public void setOffice(Office office) { this.office = office; } }
2,757
0.591896
0.58864
134
19.626865
20.125973
156
false
false
0
0
0
0
0
0
0.343284
false
false
13
9610b5f81d997a67846ca208b39d25305a198ca3
13,606,456,435,291
3654e5053a313bd92832c2091b2dc3d4d79308ed
/tags/release-0.3/src/main/java/ru/swing/html/builder/.svn/text-base/Builder.java.svn-base
290a31bd0e8a18d402f2f8ef618e68452522f7a3
[]
no_license
papirosko/swinghtmltemplate
https://github.com/papirosko/swinghtmltemplate
a4982525273306b5c53d770baf887a591e867f01
44eb255459cb21a3d5530896009a0f64768718dc
refs/heads/master
2021-01-01T05:10:31.571000
2016-05-24T07:55:52
2016-05-24T07:55:52
59,552,215
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ru.swing.html.builder; import javax.swing.*; import java.awt.*; /** * <pre> * User: Penkov Vladimir * Date: 26.11.2010 * Time: 12:25:36 * </pre> */ public class Builder extends JFrame { private static Builder instance; public Builder() throws HeadlessException { instance = this; setTitle("SwingHtmlTemplate buider"); setSize(640, 480); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); setLocation((screenSize.width - getWidth()) / 2, (screenSize.height - getHeight()) / 3); setDefaultCloseOperation(EXIT_ON_CLOSE); MainPanel panel = new MainPanel(); getContentPane().add(panel.getRootPanel()); } public static Builder getInstance() { return instance; } public static void main(String[] args) { new Builder().setVisible(true); } }
UTF-8
Java
883
Builder.java.svn-base
Java
[ { "context": "swing.*;\nimport java.awt.*;\n\n/**\n * <pre>\n * User: Penkov Vladimir\n * Date: 26.11.2010\n * Time: 12:25:36\n * </pre>\n ", "end": 111, "score": 0.9998429417610168, "start": 96, "tag": "NAME", "value": "Penkov Vladimir" } ]
null
[]
package ru.swing.html.builder; import javax.swing.*; import java.awt.*; /** * <pre> * User: <NAME> * Date: 26.11.2010 * Time: 12:25:36 * </pre> */ public class Builder extends JFrame { private static Builder instance; public Builder() throws HeadlessException { instance = this; setTitle("SwingHtmlTemplate buider"); setSize(640, 480); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); setLocation((screenSize.width - getWidth()) / 2, (screenSize.height - getHeight()) / 3); setDefaultCloseOperation(EXIT_ON_CLOSE); MainPanel panel = new MainPanel(); getContentPane().add(panel.getRootPanel()); } public static Builder getInstance() { return instance; } public static void main(String[] args) { new Builder().setVisible(true); } }
874
0.635334
0.610419
39
21.615385
22.805325
96
false
false
0
0
0
0
0
0
0.410256
false
false
0
817ed8b47dc910ab6da5653b2d9e50de9f5114b4
21,414,706,987,012
31f7ef6618f7db42f0869a4186e1fc381f2c1f25
/src/br/com/abc/javacore/io/FileWriterReaderTest.java
814af98b63eb78b2cd88332d9e2a3491987954b5
[]
no_license
Fabricio22042000/JAVA
https://github.com/Fabricio22042000/JAVA
244a1f98c35bbaa8d8f48280f71b00cce714a0f0
ce7dd643cead75edfa3f8ff7f76484ac5eb05216
refs/heads/master
2022-12-19T05:45:13.287000
2020-09-25T22:43:15
2020-09-25T22:43:15
298,693,331
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.com.abc.javacore.io; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; public class FileWriterReaderTest { public static void main(String[] args) { File file = new File("Arquivo.txt"); Path path = Paths.get("testando;txt"); try(FileWriter fw = new FileWriter(file); FileReader fr = new FileReader(file)){ fw.write("Fabricio Moura: está aprendendo a classe File do JAVA!\nE ele está na aula 96 do DevDojo"); fw.flush(); char[] in = new char[500]; int size = fr.read(in); System.out.println("Tamanho: " + size); for(char c : in) { System.out.print(c); } }catch(IOException e) { e.printStackTrace(); } /*try { FileWriter fw = new FileWriter(file); fw.write("Fabricio Moura: est� aprendendo a classe File do JAVA!\nE ele est� na aula 96 do DevDojo"); fw.flush(); fw.close(); FileReader fr = new FileReader(file); char[] in = new char[500]; int size = fr.read(in); System.out.println("Tamanho: " + size); for(char c : in) { System.out.print(c); } } catch (IOException e) { e.printStackTrace(); } }*/ } }
UTF-8
Java
1,275
java
FileWriterReaderTest.java
Java
[ { "context": "er fr = new FileReader(file)){\r\n\t\t\t\r\n\t\t\tfw.write(\"Fabricio Moura: está aprendendo a classe File do JAVA!\\nE ele es", "end": 485, "score": 0.8821872472763062, "start": 471, "tag": "NAME", "value": "Fabricio Moura" }, { "context": "leWriter fw = new FileWriter...
null
[]
package br.com.abc.javacore.io; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; public class FileWriterReaderTest { public static void main(String[] args) { File file = new File("Arquivo.txt"); Path path = Paths.get("testando;txt"); try(FileWriter fw = new FileWriter(file); FileReader fr = new FileReader(file)){ fw.write("<NAME>: está aprendendo a classe File do JAVA!\nE ele está na aula 96 do DevDojo"); fw.flush(); char[] in = new char[500]; int size = fr.read(in); System.out.println("Tamanho: " + size); for(char c : in) { System.out.print(c); } }catch(IOException e) { e.printStackTrace(); } /*try { FileWriter fw = new FileWriter(file); fw.write("<NAME>: est� aprendendo a classe File do JAVA!\nE ele est� na aula 96 do DevDojo"); fw.flush(); fw.close(); FileReader fr = new FileReader(file); char[] in = new char[500]; int size = fr.read(in); System.out.println("Tamanho: " + size); for(char c : in) { System.out.print(c); } } catch (IOException e) { e.printStackTrace(); } }*/ } }
1,259
0.623325
0.615445
49
23.897959
21.640141
104
false
false
0
0
0
0
0
0
2.510204
false
false
0
af2bc2183e6dafc72d02f67ce9b874d36d3c2bac
13,134,010,002,826
6eb5b8447a4f07f131122585ba9069e775e50a0a
/repository/src/main/java/org/helmut/profile/repository/listener/UserValidationListener.java
334d96379669fbbaa0e127c6f23300141eec8069
[]
no_license
helmutsiegel/profile
https://github.com/helmutsiegel/profile
a93d53887be866f755317d5cd5373c61854f1ded
4fff8057efb138caf61f3ca2fb6847a85597aad5
refs/heads/main
2023-08-29T00:47:50.446000
2021-10-22T05:39:52
2021-10-22T05:39:52
365,936,272
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.helmut.profile.repository.listener; import org.helmut.profile.repository.entity.UserEntity; import javax.persistence.PrePersist; import javax.persistence.PreUpdate; import java.util.Objects; import java.util.regex.Pattern; /** * Externalized entity listener * Validates the first name, last name, and email */ public class UserValidationListener { final static String INVALID_EMAIL = "Invalid email"; final static String INVALID_FIRST_NAME = "Invalid first name!"; final static String INVALID_LAST_NAME = "Invalid last name!"; @PrePersist @PreUpdate void validate(UserEntity userEntity) { if (Objects.isNull(userEntity.getEmail()) || !Pattern.compile("^(.+)@(.+)$").matcher(userEntity.getEmail()).matches()) { throw new IllegalArgumentException(INVALID_EMAIL); } if (Objects.isNull(userEntity.getFirstName()) || "".equals(userEntity.getFirstName())) { throw new IllegalArgumentException(INVALID_FIRST_NAME); } if (Objects.isNull(userEntity.getLastName()) || "".equals(userEntity.getLastName())) { throw new IllegalArgumentException(INVALID_LAST_NAME); } } }
UTF-8
Java
1,190
java
UserValidationListener.java
Java
[]
null
[]
package org.helmut.profile.repository.listener; import org.helmut.profile.repository.entity.UserEntity; import javax.persistence.PrePersist; import javax.persistence.PreUpdate; import java.util.Objects; import java.util.regex.Pattern; /** * Externalized entity listener * Validates the first name, last name, and email */ public class UserValidationListener { final static String INVALID_EMAIL = "Invalid email"; final static String INVALID_FIRST_NAME = "Invalid first name!"; final static String INVALID_LAST_NAME = "Invalid last name!"; @PrePersist @PreUpdate void validate(UserEntity userEntity) { if (Objects.isNull(userEntity.getEmail()) || !Pattern.compile("^(.+)@(.+)$").matcher(userEntity.getEmail()).matches()) { throw new IllegalArgumentException(INVALID_EMAIL); } if (Objects.isNull(userEntity.getFirstName()) || "".equals(userEntity.getFirstName())) { throw new IllegalArgumentException(INVALID_FIRST_NAME); } if (Objects.isNull(userEntity.getLastName()) || "".equals(userEntity.getLastName())) { throw new IllegalArgumentException(INVALID_LAST_NAME); } } }
1,190
0.696639
0.696639
33
35.060608
32.545483
128
false
false
0
0
0
0
0
0
0.606061
false
false
0
8aa3afc16f637d533eb0d9edd614fd6ef4d8e280
1,176,821,046,432
dc935d5d84b051c0825cfe3dd121e67e97b16775
/ServCli/src/main/java/com/mk/bouncy_castle_test/Encrypt.java
0be078160b131b403dab60c4326093a788fde176
[]
no_license
N1te0wl1384/Crypto_Server_Client_Java
https://github.com/N1te0wl1384/Crypto_Server_Client_Java
8b487ce632574f1817523d08c86be2eadbd843c3
4b8494941206fb701584256c35af783675d80913
refs/heads/master
2023-04-16T19:33:18.503000
2020-05-13T14:16:26
2020-05-13T14:16:26
263,632,501
0
0
null
false
2021-04-30T20:26:42
2020-05-13T13:07:17
2020-05-13T14:16:29
2021-04-30T20:26:41
14
0
0
1
Java
false
false
package com.mk.bouncy_castle_test; import org.bouncycastle.cms.*; import org.bouncycastle.cms.jcajce.JceCMSContentEncryptorBuilder; import org.bouncycastle.cms.jcajce.JceKeyTransEnvelopedRecipient; import org.bouncycastle.cms.jcajce.JceKeyTransRecipient; import org.bouncycastle.cms.jcajce.JceKeyTransRecipientInfoGenerator; import org.bouncycastle.operator.OutputEncryptor; import java.io.*; import java.net.Socket; import java.security.*; import java.security.cert.CertificateEncodingException; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.util.Collection; public class Encrypt { public static byte[] encryptData(byte[] data, X509Certificate encryptionCertificate) throws CertificateEncodingException, CMSException, IOException { byte[] encryptedData = null; if (null != data && null != encryptionCertificate) { CMSEnvelopedDataGenerator cmsEnvelopedDataGenerator = new CMSEnvelopedDataGenerator(); JceKeyTransRecipientInfoGenerator jceKey = new JceKeyTransRecipientInfoGenerator(encryptionCertificate); cmsEnvelopedDataGenerator.addRecipientInfoGenerator(jceKey); CMSTypedData msg = new CMSProcessableByteArray(data); CMSEnvelopedData cmsEnvelopedData = cmsEnvelopedDataGenerator .generate(msg, new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES128_CBC) .setProvider("BC").build()); encryptedData = cmsEnvelopedData.getEncoded(); } return encryptedData; } public static byte[] decryptData( byte[] encryptedData, PrivateKey decryptionKey) throws CMSException { byte[] decryptedData = null; if (null != encryptedData && null != decryptionKey) { CMSEnvelopedData envelopedData = new CMSEnvelopedData(encryptedData); Collection<RecipientInformation> recipients = envelopedData.getRecipientInfos().getRecipients(); KeyTransRecipientInformation recipientInfo = (KeyTransRecipientInformation) recipients.iterator().next(); JceKeyTransRecipient recipient = new JceKeyTransEnvelopedRecipient(decryptionKey); return recipientInfo.getContent(recipient); } return decryptedData; } public X509Certificate getCert(InputStream ois) throws IOException, CertificateException { CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte buffer[] = new byte[2048]; baos.write(buffer, 0, ois.read(buffer)); byte[] byteCert = baos.toByteArray(); ByteArrayInputStream bais = new ByteArrayInputStream(byteCert); X509Certificate cert = (X509Certificate)certificateFactory.generateCertificate(bais); System.out.println("Certificate obtained"); return cert; } public void pushCert(X509Certificate cert, OutputStream out) throws CertificateException, IOException { byte[] certArray = cert.getEncoded(); out.write(certArray); out.flush(); System.out.println("Certificate sent"); } public String decryptionHandler(PrivateKey key, InputStream is) throws KeyStoreException, IOException, UnrecoverableKeyException, NoSuchAlgorithmException, CertificateException, CMSException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; baos.write(buffer, 0, is.read(buffer)); byte[] encryptedMessage = baos.toByteArray(); byte[] decryptedMessage = decryptData(encryptedMessage, key); return new String(decryptedMessage); } // make this method more generic public PrivateKey initializeKeystore(char[] keystorePass, char[] keyPass, String keystorePath) throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException, UnrecoverableKeyException { KeyStore keystore = KeyStore.getInstance("PKCS12"); keystore.load(new FileInputStream(keystorePath), keystorePass); PrivateKey key = (PrivateKey) keystore.getKey("mykey", keyPass); return key; } }
UTF-8
Java
4,537
java
Encrypt.java
Java
[]
null
[]
package com.mk.bouncy_castle_test; import org.bouncycastle.cms.*; import org.bouncycastle.cms.jcajce.JceCMSContentEncryptorBuilder; import org.bouncycastle.cms.jcajce.JceKeyTransEnvelopedRecipient; import org.bouncycastle.cms.jcajce.JceKeyTransRecipient; import org.bouncycastle.cms.jcajce.JceKeyTransRecipientInfoGenerator; import org.bouncycastle.operator.OutputEncryptor; import java.io.*; import java.net.Socket; import java.security.*; import java.security.cert.CertificateEncodingException; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.util.Collection; public class Encrypt { public static byte[] encryptData(byte[] data, X509Certificate encryptionCertificate) throws CertificateEncodingException, CMSException, IOException { byte[] encryptedData = null; if (null != data && null != encryptionCertificate) { CMSEnvelopedDataGenerator cmsEnvelopedDataGenerator = new CMSEnvelopedDataGenerator(); JceKeyTransRecipientInfoGenerator jceKey = new JceKeyTransRecipientInfoGenerator(encryptionCertificate); cmsEnvelopedDataGenerator.addRecipientInfoGenerator(jceKey); CMSTypedData msg = new CMSProcessableByteArray(data); CMSEnvelopedData cmsEnvelopedData = cmsEnvelopedDataGenerator .generate(msg, new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES128_CBC) .setProvider("BC").build()); encryptedData = cmsEnvelopedData.getEncoded(); } return encryptedData; } public static byte[] decryptData( byte[] encryptedData, PrivateKey decryptionKey) throws CMSException { byte[] decryptedData = null; if (null != encryptedData && null != decryptionKey) { CMSEnvelopedData envelopedData = new CMSEnvelopedData(encryptedData); Collection<RecipientInformation> recipients = envelopedData.getRecipientInfos().getRecipients(); KeyTransRecipientInformation recipientInfo = (KeyTransRecipientInformation) recipients.iterator().next(); JceKeyTransRecipient recipient = new JceKeyTransEnvelopedRecipient(decryptionKey); return recipientInfo.getContent(recipient); } return decryptedData; } public X509Certificate getCert(InputStream ois) throws IOException, CertificateException { CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte buffer[] = new byte[2048]; baos.write(buffer, 0, ois.read(buffer)); byte[] byteCert = baos.toByteArray(); ByteArrayInputStream bais = new ByteArrayInputStream(byteCert); X509Certificate cert = (X509Certificate)certificateFactory.generateCertificate(bais); System.out.println("Certificate obtained"); return cert; } public void pushCert(X509Certificate cert, OutputStream out) throws CertificateException, IOException { byte[] certArray = cert.getEncoded(); out.write(certArray); out.flush(); System.out.println("Certificate sent"); } public String decryptionHandler(PrivateKey key, InputStream is) throws KeyStoreException, IOException, UnrecoverableKeyException, NoSuchAlgorithmException, CertificateException, CMSException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; baos.write(buffer, 0, is.read(buffer)); byte[] encryptedMessage = baos.toByteArray(); byte[] decryptedMessage = decryptData(encryptedMessage, key); return new String(decryptedMessage); } // make this method more generic public PrivateKey initializeKeystore(char[] keystorePass, char[] keyPass, String keystorePath) throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException, UnrecoverableKeyException { KeyStore keystore = KeyStore.getInstance("PKCS12"); keystore.load(new FileInputStream(keystorePath), keystorePass); PrivateKey key = (PrivateKey) keystore.getKey("mykey", keyPass); return key; } }
4,537
0.686797
0.678863
100
43.369999
36.399906
213
false
false
0
0
0
0
0
0
0.8
false
false
0
470b159020a73d4bdad7a17f99d0d663f6c05318
1,176,821,045,137
876565f94aac00817cdb94c1cc244a4fdfcd0940
/project/crawler/src/main/java/com/mwx/citool/crawler/app/AppConfigReader.java
2eabf6d92f7b6f658ee7461de1b2f40d6bb44f97
[]
no_license
KaterKarlo/citool
https://github.com/KaterKarlo/citool
c5c5820ee0e5b01aaaef22ac28b99c85c0507cfc
30b6ff945676e054c16156e5475ebb8fa74058c4
refs/heads/master
2021-01-10T19:50:13.316000
2015-08-13T14:59:58
2015-08-13T14:59:58
40,664,641
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mwx.citool.crawler.app; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ResourceBundle; /** * Copyright mediaworx berlin AG, Berlin, Germany * Creator: Joern Sattler, sattler@mediaworx.com * Date: 17.03.15 * Time: 09:51 * To change this template use File | Settings | File Templates. */ public class AppConfigReader { private final static Logger LOGGER = LoggerFactory.getLogger(AppConfigReader.class); private static final String APP_CONFIG_BUNDLE = "app"; private static final String VALUE_SEPARATOR = ";"; public static String[] readConfigValues(String configKey) { String[] values = null; try { ResourceBundle appConfig = ResourceBundle.getBundle(APP_CONFIG_BUNDLE); String config = appConfig.getString(configKey); values = readValues(config); } catch (Exception e) { LOGGER.debug("failed to read app config for key ["+configKey+"]"); } return values; } private static String[] readValues(String config) { String[] values = config.split(VALUE_SEPARATOR); if(values.length > 0) return values; // ";".split(";") --> length is 0 else return null; } }
UTF-8
Java
1,280
java
AppConfigReader.java
Java
[ { "context": "t mediaworx berlin AG, Berlin, Germany\n * Creator: Joern Sattler, sattler@mediaworx.com\n * Date: 17.03.15\n * Time:", "end": 208, "score": 0.9998804330825806, "start": 195, "tag": "NAME", "value": "Joern Sattler" }, { "context": "lin AG, Berlin, Germany\n * Creator: J...
null
[]
package com.mwx.citool.crawler.app; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ResourceBundle; /** * Copyright mediaworx berlin AG, Berlin, Germany * Creator: <NAME>, <EMAIL> * Date: 17.03.15 * Time: 09:51 * To change this template use File | Settings | File Templates. */ public class AppConfigReader { private final static Logger LOGGER = LoggerFactory.getLogger(AppConfigReader.class); private static final String APP_CONFIG_BUNDLE = "app"; private static final String VALUE_SEPARATOR = ";"; public static String[] readConfigValues(String configKey) { String[] values = null; try { ResourceBundle appConfig = ResourceBundle.getBundle(APP_CONFIG_BUNDLE); String config = appConfig.getString(configKey); values = readValues(config); } catch (Exception e) { LOGGER.debug("failed to read app config for key ["+configKey+"]"); } return values; } private static String[] readValues(String config) { String[] values = config.split(VALUE_SEPARATOR); if(values.length > 0) return values; // ";".split(";") --> length is 0 else return null; } }
1,259
0.642187
0.63125
48
25.6875
25.474789
88
false
false
0
0
0
0
0
0
0.5
false
false
0
1ef8607047efa54f9b143cc3a9be60c7fc70d2f4
5,823,975,658,649
065366e0edfe0d71ce7444f43920af53f7d6097c
/Users/Rayl/Documents/ShappireEstate/src/java/db/DBService.java
e3cc251ce09b42c7559e92373e2b66f055ef5699
[]
no_license
rayl15/crudnews
https://github.com/rayl15/crudnews
c4eb6f937bd053b55591a7df1facf1395253b595
cc01564618efb26933a5b36ddd3f15f800df77af
refs/heads/master
2021-01-16T21:36:48.426000
2016-07-26T08:27:11
2016-07-26T08:27:11
64,190,133
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package db; import java.sql.*; public class DBService { public static int updateData(String dmlQuery){ try{ Class.forName("com.mysql.jdbc.Driver"); String url="jdbc:mysql://127.001:3306/property"; Connection con; con=DriverManager.getConnection(url,"root","007"); Statement st=con.createStatement(); int ur=st.executeUpdate(dmlQuery); return ur; }catch(Exception e){ System.out.println("SELECT QUERY ERRROR :"+e.getMessage()); return -1; } } public static ResultSet selectData(String projQuery){ try{ Class.forName("com.mysql.jdbc.Driver"); String url="jdbc:mysql://127.001:3306/property"; Connection con; con=DriverManager.getConnection(url,"root","007"); Statement st=con.createStatement(); ResultSet rs=st.executeQuery(projQuery); return rs; }catch(Exception e){ System.out.println("SELECT QUERY ERRROR :"+e.getMessage()); return null; } } }
UTF-8
Java
1,172
java
DBService.java
Java
[]
null
[]
package db; import java.sql.*; public class DBService { public static int updateData(String dmlQuery){ try{ Class.forName("com.mysql.jdbc.Driver"); String url="jdbc:mysql://127.001:3306/property"; Connection con; con=DriverManager.getConnection(url,"root","007"); Statement st=con.createStatement(); int ur=st.executeUpdate(dmlQuery); return ur; }catch(Exception e){ System.out.println("SELECT QUERY ERRROR :"+e.getMessage()); return -1; } } public static ResultSet selectData(String projQuery){ try{ Class.forName("com.mysql.jdbc.Driver"); String url="jdbc:mysql://127.001:3306/property"; Connection con; con=DriverManager.getConnection(url,"root","007"); Statement st=con.createStatement(); ResultSet rs=st.executeQuery(projQuery); return rs; }catch(Exception e){ System.out.println("SELECT QUERY ERRROR :"+e.getMessage()); return null; } } }
1,172
0.546075
0.523038
56
19.910715
21.001936
71
false
false
0
0
0
0
0
0
0.428571
false
false
0
3bad2e407184529e50348559bedff121abaafcf1
10,943,576,675,911
a11765f046d2f8874d13e29b0773e54d921287b8
/AccessHDFSthruJavaAPI/src/bdpuh/hw2/WorkerThread.java
be73dc8b59f18f13f74c4c70b8805fe50f3908db
[]
no_license
mashhype/Hadoop
https://github.com/mashhype/Hadoop
5965094cef5647420decad46fd7e2b59b4457e45
e91954449165e4ff240862d1b9b5eb26bbed1d4c
refs/heads/master
2021-01-13T02:08:44.919000
2015-03-04T19:55:02
2015-03-04T19:55:02
31,676,314
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package bdpuh.hw2; /** * * @author hdadmin */ public class WorkerThread implements Runnable { public WorkerThread() { } @Override public void run() { //System.out.println(Thread.currentThread().getName() + " Beginning job"); processCommand(); //System.out.println(Thread.currentThread().getName() + " Ending job"); } private void processCommand() { try { Thread.sleep(100); } catch (InterruptedException e) { } } }
UTF-8
Java
715
java
WorkerThread.java
Java
[ { "context": " editor.\n */\npackage bdpuh.hw2;\n\n/**\n *\n * @author hdadmin\n */\npublic class WorkerThread implements Runnable", "end": 230, "score": 0.999637246131897, "start": 223, "tag": "USERNAME", "value": "hdadmin" } ]
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package bdpuh.hw2; /** * * @author hdadmin */ public class WorkerThread implements Runnable { public WorkerThread() { } @Override public void run() { //System.out.println(Thread.currentThread().getName() + " Beginning job"); processCommand(); //System.out.println(Thread.currentThread().getName() + " Ending job"); } private void processCommand() { try { Thread.sleep(100); } catch (InterruptedException e) { } } }
715
0.604196
0.598601
30
22.833334
24.702339
83
false
false
0
0
0
0
0
0
0.833333
false
false
0
ab25681968a65df7301257ecb26e1572aba7a304
26,843,545,607,915
8f36b5118ff6e346f2bce9df68e8328957c101dc
/src/com/wxy/graph/struct/AdjListGraph.java
ef02d787ffd30e07441267dff602d8c212d8f62b
[ "Apache-2.0" ]
permissive
satellite-space/dataStruct
https://github.com/satellite-space/dataStruct
7b66246ad9cf26aa0dce794d30ce422689141583
31f644dcbdfd32bd4fc9b3ddf419c987d4d6dfc5
refs/heads/master
2022-03-20T23:10:35.825000
2019-12-02T15:52:03
2019-12-02T15:52:03
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.wxy.graph.struct; import com.wxy.stack.Queue; import com.wxy.stack.impl.ArrayQueue; import java.util.Scanner; /** * <p> * 图——邻接表 * 只实现网图的创建,其他方法等后续需要使用时再创建 * </p> * * @author wxy * @version 1.0 * @create 2019/11/7 22:10 */ public class AdjListGraph { private class EdgeNode { int adjvex; int weight; EdgeNode next; } private class VertexNode { Object data; EdgeNode firstedge; } private VertexNode[] adjList; private int numVertexes, numEdges; private boolean[] visited; private Queue queue; public AdjListGraph(int numVertexes, int numEdges) { this.numVertexes = numVertexes; this.numEdges = numEdges; this.adjList = new VertexNode[numVertexes]; for (int i = 0; i < numVertexes; i++) { adjList[i] = new VertexNode(); } createNetwork(); } private void createNetwork() { Scanner scan = new Scanner(System.in); for (int i = 0; i < numVertexes; i++) { System.out.println("请输入第" + i + "个结点的信息"); adjList[i].data = scan.next(); } // 循环对每条边进行赋值 EdgeNode node; for (int k = 0; k < numEdges; k++) { System.out.println("输入边(vi和vj上的顶点序号):"); int i = scan.nextInt(); int j = scan.nextInt(); node = new EdgeNode(); node.adjvex = j; node.next = adjList[i].firstedge; adjList[i].firstedge = node; node = new EdgeNode(); node.adjvex = i; node.next = adjList[j].firstedge; adjList[j].firstedge = node; } } public void traverseOfDFS() { visited = new boolean[numVertexes]; for (int i = 0; i < numVertexes; i++) { if (!visited[i]) { searchDFS(this, i); } } } private void searchDFS(AdjListGraph graph, int i) { visited[i] = true; System.out.print(graph.adjList[i].data + "\t"); EdgeNode node = graph.adjList[i].firstedge; while (null != node) { if (!visited[node.adjvex]) { searchDFS(graph, node.adjvex); } node = node.next; } } public void traverseOfHFS() { queue = new ArrayQueue(this.numVertexes); visited = new boolean[this.numVertexes]; searchHFS(this); } private void searchHFS(AdjListGraph graph) { for (int i = 0; i < graph.numVertexes; i++) { if (!visited[i]) { visited[i] = true; System.out.print(graph.adjList[i].data + "\t"); queue.add(graph.adjList[i]); while (!queue.isEmpty()) { queue.remove(); EdgeNode node = graph.adjList[i].firstedge; while (null != node) { if (!visited[node.adjvex]) { visited[node.adjvex] = true; System.out.print(graph.adjList[node.adjvex].data + "\t"); queue.add(graph.adjList[node.adjvex]); } node = node.next; } } } } } }
UTF-8
Java
3,438
java
AdjListGraph.java
Java
[ { "context": " 只实现网图的创建,其他方法等后续需要使用时再创建\n * </p>\n *\n * @author wxy\n * @version 1.0\n * @create 2019/11/7 22:10\n */\npu", "end": 207, "score": 0.999653697013855, "start": 204, "tag": "USERNAME", "value": "wxy" } ]
null
[]
package com.wxy.graph.struct; import com.wxy.stack.Queue; import com.wxy.stack.impl.ArrayQueue; import java.util.Scanner; /** * <p> * 图——邻接表 * 只实现网图的创建,其他方法等后续需要使用时再创建 * </p> * * @author wxy * @version 1.0 * @create 2019/11/7 22:10 */ public class AdjListGraph { private class EdgeNode { int adjvex; int weight; EdgeNode next; } private class VertexNode { Object data; EdgeNode firstedge; } private VertexNode[] adjList; private int numVertexes, numEdges; private boolean[] visited; private Queue queue; public AdjListGraph(int numVertexes, int numEdges) { this.numVertexes = numVertexes; this.numEdges = numEdges; this.adjList = new VertexNode[numVertexes]; for (int i = 0; i < numVertexes; i++) { adjList[i] = new VertexNode(); } createNetwork(); } private void createNetwork() { Scanner scan = new Scanner(System.in); for (int i = 0; i < numVertexes; i++) { System.out.println("请输入第" + i + "个结点的信息"); adjList[i].data = scan.next(); } // 循环对每条边进行赋值 EdgeNode node; for (int k = 0; k < numEdges; k++) { System.out.println("输入边(vi和vj上的顶点序号):"); int i = scan.nextInt(); int j = scan.nextInt(); node = new EdgeNode(); node.adjvex = j; node.next = adjList[i].firstedge; adjList[i].firstedge = node; node = new EdgeNode(); node.adjvex = i; node.next = adjList[j].firstedge; adjList[j].firstedge = node; } } public void traverseOfDFS() { visited = new boolean[numVertexes]; for (int i = 0; i < numVertexes; i++) { if (!visited[i]) { searchDFS(this, i); } } } private void searchDFS(AdjListGraph graph, int i) { visited[i] = true; System.out.print(graph.adjList[i].data + "\t"); EdgeNode node = graph.adjList[i].firstedge; while (null != node) { if (!visited[node.adjvex]) { searchDFS(graph, node.adjvex); } node = node.next; } } public void traverseOfHFS() { queue = new ArrayQueue(this.numVertexes); visited = new boolean[this.numVertexes]; searchHFS(this); } private void searchHFS(AdjListGraph graph) { for (int i = 0; i < graph.numVertexes; i++) { if (!visited[i]) { visited[i] = true; System.out.print(graph.adjList[i].data + "\t"); queue.add(graph.adjList[i]); while (!queue.isEmpty()) { queue.remove(); EdgeNode node = graph.adjList[i].firstedge; while (null != node) { if (!visited[node.adjvex]) { visited[node.adjvex] = true; System.out.print(graph.adjList[node.adjvex].data + "\t"); queue.add(graph.adjList[node.adjvex]); } node = node.next; } } } } } }
3,438
0.493972
0.488547
120
26.65
19.040155
85
false
false
0
0
0
0
0
0
0.558333
false
false
0
901fbf39464c09d65e9a216cc06c6334e374b75b
28,097,676,057,740
968038c15968034af0f2348797879555ff83c792
/Search/src/test/Dom.java
589c1e363cea959d17ceacd05e4d3bdb4da5517b
[]
no_license
magical930525/Search
https://github.com/magical930525/Search
f47d8a6adb6ce345ea4265f76556753b734924ca
3ab9816f737027e52066693c611c942d0811f0da
refs/heads/master
2021-01-18T23:31:57.661000
2015-05-13T11:24:35
2015-05-13T11:24:35
35,542,797
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package test; import java.io.File; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import model.News; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.NodeList; import util.DBConnection; public class Dom { public static int index=0; public static List<News> read(String path) throws Exception { // step 1:获得DOM解析器工厂 // 工厂的作用是创建具体的解析器 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); // step 2:获得具体的dom解析器 DocumentBuilder db = dbf.newDocumentBuilder(); // step 3:解析一个xml文档,获得Document对象(根节点) // 此文档放在项目目录下即可 Document document = db.parse(new File(path)); // 根据标签名访问节点 System.out.println("处理该文档的DomImplementation对象 = " + document.getImplementation()); NodeList list = document.getElementsByTagName("li"); System.out.println("list length: " + list.getLength()); List<News> newList = new ArrayList<News>(); // 遍历每一个节点 int s=read(); for (int i = 0; i < list.getLength(); ++i) { News a1 = new News(); System.out.println("----------------------"); // 获得元素,将节点强制转换为元素 Element element = (Element) list.item(i); // 此时element就是一个具体的元素 // 获取子元素:子元素title只有一个节点,之后通过getNodeValue方法获取节点的值 String content0 = element.getElementsByTagName("a").item(0) .getNodeValue(); System.out.println(content0);// 此处打印出为null // 因为节点getNodeValue的值永远为null // 解决方法:加上getFirstChild() String content = element.getElementsByTagName("a").item(0) .getFirstChild().getNodeValue(); System.out.println("a: " + content);// 此处打印出标题 a1.setTitle(content); // 后面类似处理即可: content = element.getElementsByTagName("span").item(0) .getFirstChild().getNodeValue(); System.out.println("span: " + content); a1.setTime(content); content = element.getElementsByTagName("p").item(0).getFirstChild() .getNodeValue(); System.out.println("p: " + content); a1.setP(content); NamedNodeMap url = element.getElementsByTagName("a").item(0) .getAttributes(); String x = url.item(0).getNodeValue(); System.out.println("href: " + x); a1.setUrl(x); System.out.println(list.getLength()); System.out.println(s+"::::;"); if(s==list.getLength()){ System.out.println("不需要插入"); }else{ addNew(a1);//插入数据 } newList.add(a1); } return newList; } public static int read(){ DBConnection dbo = new DBConnection(); dbo.open(); String sql="select * from news"; try { ResultSet rs=dbo.executeQuery(sql); while(rs.next()){ index++; System.out.println(index); } return index; } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return index; } public static void addNew(News news) { String sql = "insert into news(title,time,url,p) values('" + news.getTitle() + "','" + news.getTime() + "','" + news.getUrl() + "','" + news.getP() + "')"; // System.out.println(sql); DBConnection dbo = new DBConnection(); dbo.open(); try { dbo.executeUpdate(sql); } catch (Exception e) { e.printStackTrace(); } finally { dbo.close(); } } }
GB18030
Java
3,773
java
Dom.java
Java
[]
null
[]
package test; import java.io.File; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import model.News; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.NodeList; import util.DBConnection; public class Dom { public static int index=0; public static List<News> read(String path) throws Exception { // step 1:获得DOM解析器工厂 // 工厂的作用是创建具体的解析器 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); // step 2:获得具体的dom解析器 DocumentBuilder db = dbf.newDocumentBuilder(); // step 3:解析一个xml文档,获得Document对象(根节点) // 此文档放在项目目录下即可 Document document = db.parse(new File(path)); // 根据标签名访问节点 System.out.println("处理该文档的DomImplementation对象 = " + document.getImplementation()); NodeList list = document.getElementsByTagName("li"); System.out.println("list length: " + list.getLength()); List<News> newList = new ArrayList<News>(); // 遍历每一个节点 int s=read(); for (int i = 0; i < list.getLength(); ++i) { News a1 = new News(); System.out.println("----------------------"); // 获得元素,将节点强制转换为元素 Element element = (Element) list.item(i); // 此时element就是一个具体的元素 // 获取子元素:子元素title只有一个节点,之后通过getNodeValue方法获取节点的值 String content0 = element.getElementsByTagName("a").item(0) .getNodeValue(); System.out.println(content0);// 此处打印出为null // 因为节点getNodeValue的值永远为null // 解决方法:加上getFirstChild() String content = element.getElementsByTagName("a").item(0) .getFirstChild().getNodeValue(); System.out.println("a: " + content);// 此处打印出标题 a1.setTitle(content); // 后面类似处理即可: content = element.getElementsByTagName("span").item(0) .getFirstChild().getNodeValue(); System.out.println("span: " + content); a1.setTime(content); content = element.getElementsByTagName("p").item(0).getFirstChild() .getNodeValue(); System.out.println("p: " + content); a1.setP(content); NamedNodeMap url = element.getElementsByTagName("a").item(0) .getAttributes(); String x = url.item(0).getNodeValue(); System.out.println("href: " + x); a1.setUrl(x); System.out.println(list.getLength()); System.out.println(s+"::::;"); if(s==list.getLength()){ System.out.println("不需要插入"); }else{ addNew(a1);//插入数据 } newList.add(a1); } return newList; } public static int read(){ DBConnection dbo = new DBConnection(); dbo.open(); String sql="select * from news"; try { ResultSet rs=dbo.executeQuery(sql); while(rs.next()){ index++; System.out.println(index); } return index; } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return index; } public static void addNew(News news) { String sql = "insert into news(title,time,url,p) values('" + news.getTitle() + "','" + news.getTime() + "','" + news.getUrl() + "','" + news.getP() + "')"; // System.out.println(sql); DBConnection dbo = new DBConnection(); dbo.open(); try { dbo.executeUpdate(sql); } catch (Exception e) { e.printStackTrace(); } finally { dbo.close(); } } }
3,773
0.637511
0.630467
129
24.426357
18.525814
70
false
false
0
0
0
0
0
0
2.48062
false
false
0
c1c6e23845b79b78abede85d375478d683b0ce16
32,126,355,387,148
1ac145ce1bb0b9d83af0d681b304f3510ca7427e
/src/main/java/com/edu/nju/kanbanboard/model/domain/KBBoard.java
273504f220a082385e91dfe984e231eb3aa37c6c
[]
no_license
yuzhouzhuang/NJU-GraduationProject-Kanban-Backend
https://github.com/yuzhouzhuang/NJU-GraduationProject-Kanban-Backend
023b5fcb1e410adcf5b54d91e3237a01a34b7b51
d0b388866e0f9508dfbb650e8b3a4b34ecfad8e0
refs/heads/master
2022-01-19T21:07:23.197000
2019-05-22T09:24:46
2019-05-22T09:24:46
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.edu.nju.kanbanboard.model.domain; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.Data; import org.hibernate.annotations.Proxy; import javax.persistence.*; import javax.validation.constraints.NotBlank; import java.io.Serializable; import java.util.*; @Data @Entity @Table(name = "kb_board") @Proxy(lazy = false) public class KBBoard implements Serializable { private static final long serialVersionUID = -111835654956927440L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long boardId; @OneToMany(mappedBy = "kbBoard",cascade = CascadeType.ALL,fetch = FetchType.EAGER) private Set<KBColumn> columns = new HashSet<>(); @ManyToMany( mappedBy = "kbBoards") @JsonIgnore private Set<KBUser> kbUsers = new HashSet<>(); private Long ownerId; @NotBlank(message = "看板名称不能为空") private String boardName; private Date createDate; @Override public boolean equals(Object x){ if(this == x)return true; if(x == null)return false; if(this.getClass() != x.getClass())return false; KBBoard that = (KBBoard)x; return this.boardId.equals(that.boardId); } }
UTF-8
Java
1,215
java
KBBoard.java
Java
[]
null
[]
package com.edu.nju.kanbanboard.model.domain; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.Data; import org.hibernate.annotations.Proxy; import javax.persistence.*; import javax.validation.constraints.NotBlank; import java.io.Serializable; import java.util.*; @Data @Entity @Table(name = "kb_board") @Proxy(lazy = false) public class KBBoard implements Serializable { private static final long serialVersionUID = -111835654956927440L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long boardId; @OneToMany(mappedBy = "kbBoard",cascade = CascadeType.ALL,fetch = FetchType.EAGER) private Set<KBColumn> columns = new HashSet<>(); @ManyToMany( mappedBy = "kbBoards") @JsonIgnore private Set<KBUser> kbUsers = new HashSet<>(); private Long ownerId; @NotBlank(message = "看板名称不能为空") private String boardName; private Date createDate; @Override public boolean equals(Object x){ if(this == x)return true; if(x == null)return false; if(this.getClass() != x.getClass())return false; KBBoard that = (KBBoard)x; return this.boardId.equals(that.boardId); } }
1,215
0.702252
0.687239
46
25.065218
21.654804
86
false
false
0
0
0
0
0
0
0.478261
false
false
0
bcc30c8c62f7f550e6742063585ea9cec6f933cb
20,727,512,173,973
8339b20ad822b920dde33d1b6873a5d71b4ff67a
/app/src/main/java/com/example/chinenzl/wintec_cbite/StudentCourseAdapter.java
336e9442605220ce0f6267256f494987cdc94e68
[]
no_license
liamzl/Wintec_CBITE
https://github.com/liamzl/Wintec_CBITE
e6cbce5abede9554db1c1b5d1d8b129240977b7b
fed55c4bd84fe5e777b26d9076f6b73f3c92aeaa
refs/heads/master
2020-04-02T12:16:01.493000
2018-11-12T02:42:07
2018-11-12T02:42:07
154,426,111
0
1
null
false
2018-11-04T00:02:21
2018-10-24T02:24:02
2018-10-26T05:34:29
2018-11-04T00:02:21
439
0
1
0
Java
false
null
package com.example.chinenzl.wintec_cbite; import android.content.Context; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import com.example.chinenzl.model.Course; import java.util.List; public class StudentCourseAdapter extends ArrayAdapter<Course> { public StudentCourseAdapter(@NonNull Context context, List<Course> arrCourse) { super(context, R.layout.activity_student_course_adapter, arrCourse); } @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { LayoutInflater buckysInflater = LayoutInflater.from(getContext()); View courseView = buckysInflater.inflate(R.layout.activity_student_course_adapter, parent, false); Course coursePackage = getItem(position); TextView courseCode = (TextView) courseView.findViewById(R.id.checkBox); TextView courseName = (TextView) courseView.findViewById(R.id.textViewName); // dynamically update the text from the array courseCode.setText(coursePackage.code); courseName.setText(coursePackage.name); return courseView; } }
UTF-8
Java
1,332
java
StudentCourseAdapter.java
Java
[]
null
[]
package com.example.chinenzl.wintec_cbite; import android.content.Context; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import com.example.chinenzl.model.Course; import java.util.List; public class StudentCourseAdapter extends ArrayAdapter<Course> { public StudentCourseAdapter(@NonNull Context context, List<Course> arrCourse) { super(context, R.layout.activity_student_course_adapter, arrCourse); } @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { LayoutInflater buckysInflater = LayoutInflater.from(getContext()); View courseView = buckysInflater.inflate(R.layout.activity_student_course_adapter, parent, false); Course coursePackage = getItem(position); TextView courseCode = (TextView) courseView.findViewById(R.id.checkBox); TextView courseName = (TextView) courseView.findViewById(R.id.textViewName); // dynamically update the text from the array courseCode.setText(coursePackage.code); courseName.setText(coursePackage.name); return courseView; } }
1,332
0.755255
0.755255
36
36
30.375429
106
false
false
0
0
0
0
0
0
0.75
false
false
0
76e61ec026d277a6acfcaf538a5daf8d3dd22fdf
16,149,077,044,656
b0902fce08435ae7df7f75f480a7fb8b52581b90
/src/main/java/com/beniregev/demos_and_tutorials/examples/JDBCExample.java
4ad5effc7450214e4e12727b3624335d1defef2d
[]
no_license
beniregev/demos_and_tutorials
https://github.com/beniregev/demos_and_tutorials
1e9d93d06f61aec300aa1c32449b57e70ae2eef1
6c4a992955895a98fe4c4b446d7e62f0d938f5dd
refs/heads/master
2023-08-09T10:03:57.181000
2023-02-28T21:50:27
2023-02-28T21:50:27
231,241,967
0
1
null
false
2023-07-23T01:41:15
2020-01-01T17:03:44
2023-02-07T10:55:34
2023-07-23T01:41:14
4,134
0
1
1
Java
false
false
package com.beniregev.demos_and_tutorials.examples; import java.sql.*; public class JDBCExample { private static final int MS_IN_SEC = 1000; private static final int MAX_ROWS_TO_RETRIEVE_AT_ONE_TIME = 10000; public static void main(String[] args) { System.out.println("-------- PostgreSQL JDBC Connection Testing ------------"); try { Class.forName("org.postgresql.Driver"); } catch (ClassNotFoundException e) { System.out.println("Where is your PostgreSQL JDBC Driver? Include in your library path!"); e.printStackTrace(); return; } System.out.println("PostgreSQL JDBC Driver Registered!"); try { //Connection connection = DriverManager.getConnection( // "jdbc:postgresql://localhost:5432/cookbook","postgres","admin"); Connection connection = DriverManager.getConnection( "jdbc:postgresql://hh-pgsql-public.ebi.ac.uk:5432/pfmegrnargs", "reader", "NWDMCE5xdipIjRrp"); if (connection != null) { System.out.println("You made it, take control your database now!"); Statement statement = connection.createStatement(); statement.setFetchSize(MAX_ROWS_TO_RETRIEVE_AT_ONE_TIME); System.out.println("Reading car records..."); System.out.printf("%-10.10s %-10.10s %-10.10s %-10.10s%n", "rowCount", "dbid", "created", "last", "upi"); final long retrieveStart = System.currentTimeMillis(); ResultSet resultSet = statement.executeQuery("SELECT * FROM xref WHERE timestamp > '2019-01-05'"); //ResultSet resultSet = preparedStatement.executeQuery(); final double seconds = (System.currentTimeMillis() - retrieveStart) / MS_IN_SEC; long rowCount = 0; while (resultSet.next()) { rowCount++; System.out.printf("%-10.10s %-10.10s %-10.10s %-10.10s%n", resultSet.getShort("dbid"), resultSet.getInt("created"), resultSet.getInt("last"), resultSet.getString("upi")); } resultSet.close(); System.out.println("Retrieve took " + seconds + " seconds and " + (rowCount > 0 ? rowCount : "no") + " rows retrieved"); } else { System.out.println("Failed to make connection!"); } } catch (SQLException e) { System.out.println("Connection Failed! Check output console"); e.printStackTrace(); return; } } }
UTF-8
Java
2,789
java
JDBCExample.java
Java
[]
null
[]
package com.beniregev.demos_and_tutorials.examples; import java.sql.*; public class JDBCExample { private static final int MS_IN_SEC = 1000; private static final int MAX_ROWS_TO_RETRIEVE_AT_ONE_TIME = 10000; public static void main(String[] args) { System.out.println("-------- PostgreSQL JDBC Connection Testing ------------"); try { Class.forName("org.postgresql.Driver"); } catch (ClassNotFoundException e) { System.out.println("Where is your PostgreSQL JDBC Driver? Include in your library path!"); e.printStackTrace(); return; } System.out.println("PostgreSQL JDBC Driver Registered!"); try { //Connection connection = DriverManager.getConnection( // "jdbc:postgresql://localhost:5432/cookbook","postgres","admin"); Connection connection = DriverManager.getConnection( "jdbc:postgresql://hh-pgsql-public.ebi.ac.uk:5432/pfmegrnargs", "reader", "NWDMCE5xdipIjRrp"); if (connection != null) { System.out.println("You made it, take control your database now!"); Statement statement = connection.createStatement(); statement.setFetchSize(MAX_ROWS_TO_RETRIEVE_AT_ONE_TIME); System.out.println("Reading car records..."); System.out.printf("%-10.10s %-10.10s %-10.10s %-10.10s%n", "rowCount", "dbid", "created", "last", "upi"); final long retrieveStart = System.currentTimeMillis(); ResultSet resultSet = statement.executeQuery("SELECT * FROM xref WHERE timestamp > '2019-01-05'"); //ResultSet resultSet = preparedStatement.executeQuery(); final double seconds = (System.currentTimeMillis() - retrieveStart) / MS_IN_SEC; long rowCount = 0; while (resultSet.next()) { rowCount++; System.out.printf("%-10.10s %-10.10s %-10.10s %-10.10s%n", resultSet.getShort("dbid"), resultSet.getInt("created"), resultSet.getInt("last"), resultSet.getString("upi")); } resultSet.close(); System.out.println("Retrieve took " + seconds + " seconds and " + (rowCount > 0 ? rowCount : "no") + " rows retrieved"); } else { System.out.println("Failed to make connection!"); } } catch (SQLException e) { System.out.println("Connection Failed! Check output console"); e.printStackTrace(); return; } } }
2,789
0.543564
0.522051
62
43.983871
32.516743
124
false
false
0
0
0
0
0
0
0.709677
false
false
0
0484b71b4770069a670e81141615b8d8495bf63c
22,960,895,178,494
8dcd6fac592760c5bff55349ffb2d7ce39d485cc
/org/apache/http/impl/AbstractHttpServerConnection.java
41124211868e157c206c85af41b629fdbbdf6e85
[]
no_license
andrepcg/hikam-android
https://github.com/andrepcg/hikam-android
9e3a02e0ba9a58cf8a17c5e76e2f3435969e4b3a
bf39e345a827c6498052d9df88ca58d8823178d9
refs/heads/master
2021-09-01T11:41:10.726000
2017-12-26T19:04:42
2017-12-26T19:04:42
115,447,829
2
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.apache.http.impl; import java.io.IOException; import org.apache.http.HttpConnectionMetrics; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestFactory; import org.apache.http.HttpResponse; import org.apache.http.HttpServerConnection; import org.apache.http.impl.entity.EntityDeserializer; import org.apache.http.impl.entity.EntitySerializer; import org.apache.http.io.HttpMessageParser; import org.apache.http.io.HttpMessageWriter; import org.apache.http.io.SessionInputBuffer; import org.apache.http.io.SessionOutputBuffer; import org.apache.http.params.HttpParams; @Deprecated public abstract class AbstractHttpServerConnection implements HttpServerConnection { protected abstract void assertOpen() throws IllegalStateException; public AbstractHttpServerConnection() { throw new RuntimeException("Stub!"); } protected EntityDeserializer createEntityDeserializer() { throw new RuntimeException("Stub!"); } protected EntitySerializer createEntitySerializer() { throw new RuntimeException("Stub!"); } protected HttpRequestFactory createHttpRequestFactory() { throw new RuntimeException("Stub!"); } protected HttpMessageParser createRequestParser(SessionInputBuffer buffer, HttpRequestFactory requestFactory, HttpParams params) { throw new RuntimeException("Stub!"); } protected HttpMessageWriter createResponseWriter(SessionOutputBuffer buffer, HttpParams params) { throw new RuntimeException("Stub!"); } protected void init(SessionInputBuffer inbuffer, SessionOutputBuffer outbuffer, HttpParams params) { throw new RuntimeException("Stub!"); } public HttpRequest receiveRequestHeader() throws HttpException, IOException { throw new RuntimeException("Stub!"); } public void receiveRequestEntity(HttpEntityEnclosingRequest request) throws HttpException, IOException { throw new RuntimeException("Stub!"); } protected void doFlush() throws IOException { throw new RuntimeException("Stub!"); } public void flush() throws IOException { throw new RuntimeException("Stub!"); } public void sendResponseHeader(HttpResponse response) throws HttpException, IOException { throw new RuntimeException("Stub!"); } public void sendResponseEntity(HttpResponse response) throws HttpException, IOException { throw new RuntimeException("Stub!"); } public boolean isStale() { throw new RuntimeException("Stub!"); } public HttpConnectionMetrics getMetrics() { throw new RuntimeException("Stub!"); } }
UTF-8
Java
2,760
java
AbstractHttpServerConnection.java
Java
[]
null
[]
package org.apache.http.impl; import java.io.IOException; import org.apache.http.HttpConnectionMetrics; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestFactory; import org.apache.http.HttpResponse; import org.apache.http.HttpServerConnection; import org.apache.http.impl.entity.EntityDeserializer; import org.apache.http.impl.entity.EntitySerializer; import org.apache.http.io.HttpMessageParser; import org.apache.http.io.HttpMessageWriter; import org.apache.http.io.SessionInputBuffer; import org.apache.http.io.SessionOutputBuffer; import org.apache.http.params.HttpParams; @Deprecated public abstract class AbstractHttpServerConnection implements HttpServerConnection { protected abstract void assertOpen() throws IllegalStateException; public AbstractHttpServerConnection() { throw new RuntimeException("Stub!"); } protected EntityDeserializer createEntityDeserializer() { throw new RuntimeException("Stub!"); } protected EntitySerializer createEntitySerializer() { throw new RuntimeException("Stub!"); } protected HttpRequestFactory createHttpRequestFactory() { throw new RuntimeException("Stub!"); } protected HttpMessageParser createRequestParser(SessionInputBuffer buffer, HttpRequestFactory requestFactory, HttpParams params) { throw new RuntimeException("Stub!"); } protected HttpMessageWriter createResponseWriter(SessionOutputBuffer buffer, HttpParams params) { throw new RuntimeException("Stub!"); } protected void init(SessionInputBuffer inbuffer, SessionOutputBuffer outbuffer, HttpParams params) { throw new RuntimeException("Stub!"); } public HttpRequest receiveRequestHeader() throws HttpException, IOException { throw new RuntimeException("Stub!"); } public void receiveRequestEntity(HttpEntityEnclosingRequest request) throws HttpException, IOException { throw new RuntimeException("Stub!"); } protected void doFlush() throws IOException { throw new RuntimeException("Stub!"); } public void flush() throws IOException { throw new RuntimeException("Stub!"); } public void sendResponseHeader(HttpResponse response) throws HttpException, IOException { throw new RuntimeException("Stub!"); } public void sendResponseEntity(HttpResponse response) throws HttpException, IOException { throw new RuntimeException("Stub!"); } public boolean isStale() { throw new RuntimeException("Stub!"); } public HttpConnectionMetrics getMetrics() { throw new RuntimeException("Stub!"); } }
2,760
0.747826
0.747826
82
32.658535
30.745699
134
false
false
0
0
0
0
0
0
0.5
false
false
0
918b2db525db2dc8753890505945e76ddccf2755
31,207,232,384,842
72711ee812bf571890d648ffdfb83eb50f6c2caf
/shell/src/main/java/org/springframework/roo/shell/Shell.java
1ff9db9b9c34339c8249e4b89e53ea81efc630bf
[ "Zlib" ]
permissive
martypitt/benson
https://github.com/martypitt/benson
ce2fbdd9eae4b6f71fdf1ed3831d3fbc80bf9aaf
8d7e934e294825f3f6624d3335a9e7692acd6af5
refs/heads/master
2021-01-21T12:21:28.734000
2012-01-02T07:46:11
2012-01-02T07:46:11
3,086,234
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.springframework.roo.shell; import java.io.File; import java.util.logging.Level; import org.springframework.roo.shell.ExitShellRequest; import org.springframework.roo.shell.ShellPromptAccessor; import org.springframework.roo.shell.event.ShellStatusProvider; /** * Specifies the contract for an interactive shell. * * <p> * Any interactive shell class which implements these methods can be launched by the roo-bootstrap mechanism. * * <p> * It is envisaged implementations will be provided for JLine initially, with possible implementations for * Eclipse in the future. * * @author Ben Alex * @since 1.0 */ public interface Shell extends ShellStatusProvider, ShellPromptAccessor { /** * The slot name to use with {@link #flash(Level, String, String)} if a caller wishes to modify the window title. * This may not be supported by all operating system shells. It is provided on a best-effort basis only. */ String WINDOW_TITLE_SLOT = "WINDOW_TITLE_SLOT"; /** * Presents a console prompt and allows the user to interact with the shell. The shell should not return * to the caller until the user has finished their session (by way of a "quit" or similar command). */ void promptLoop(); /** * @return null if no exit was requested, otherwise the last exit code indicated to the shell to use */ ExitShellRequest getExitShellRequest(); /** * Runs the specified command. Control will return to the caller after the command is run. * * @param line to execute (required) * @return true if the command was successful, false if there was an exception */ boolean executeCommand(String line); /** * Indicates the shell should switch into a lower-level development mode. The exact meaning varies by * shell implementation. * * @param developmentMode true if development mode should be enabled, false otherwise */ void setDevelopmentMode(boolean developmentMode); /** * Displays a progress notification to the user. This notification will ideally be displayed in a * consistent screen location by the shell implementation. * * <p> * An implementation may allow multiple messages to be displayed concurrently. So an implementation can * determine when a flash message replaces a previous flash message, callers should allocate a unique * "slot" name for their messages. It is suggested the class name of the caller be used. This way a * slot will be updated without conflicting with flash message sequences from other slots. * * <p> * Passing an empty string in as the "message" indicates the slot should be cleared. * * <p> * An implementation need not necessarily use the level or slot concepts. They are expected to be * used in most cases, though. * * @param level the importance of the message (cannot be null) * @param message to display (cannot be null, but may be empty) * @param slot the identification slot for the message (cannot be null or empty) */ void flash(Level level, String message, String slot); boolean isDevelopmentMode(); /** * Changes the "path" displayed in the shell prompt. An implementation will ensure this path is * included on the screen, taking care to merge it with the product name and handle any special * formatting requirements (such as ANSI, if supported by the implementation). * * @param path to set (can be null or empty; must NOT be formatted in any special way eg ANSI codes) */ void setPromptPath(String path); void setPromptPath(String path, boolean overrideStyle); /** * Returns the home directory of the current running shell instance * * @return the home directory of the current shell instance */ File getHome(); }
UTF-8
Java
3,696
java
Shell.java
Java
[ { "context": "ations for\n * Eclipse in the future.\n *\n * @author Ben Alex\n * @since 1.0\n */\npublic interface Shell extends ", "end": 614, "score": 0.9995453357696533, "start": 606, "tag": "NAME", "value": "Ben Alex" } ]
null
[]
package org.springframework.roo.shell; import java.io.File; import java.util.logging.Level; import org.springframework.roo.shell.ExitShellRequest; import org.springframework.roo.shell.ShellPromptAccessor; import org.springframework.roo.shell.event.ShellStatusProvider; /** * Specifies the contract for an interactive shell. * * <p> * Any interactive shell class which implements these methods can be launched by the roo-bootstrap mechanism. * * <p> * It is envisaged implementations will be provided for JLine initially, with possible implementations for * Eclipse in the future. * * @author <NAME> * @since 1.0 */ public interface Shell extends ShellStatusProvider, ShellPromptAccessor { /** * The slot name to use with {@link #flash(Level, String, String)} if a caller wishes to modify the window title. * This may not be supported by all operating system shells. It is provided on a best-effort basis only. */ String WINDOW_TITLE_SLOT = "WINDOW_TITLE_SLOT"; /** * Presents a console prompt and allows the user to interact with the shell. The shell should not return * to the caller until the user has finished their session (by way of a "quit" or similar command). */ void promptLoop(); /** * @return null if no exit was requested, otherwise the last exit code indicated to the shell to use */ ExitShellRequest getExitShellRequest(); /** * Runs the specified command. Control will return to the caller after the command is run. * * @param line to execute (required) * @return true if the command was successful, false if there was an exception */ boolean executeCommand(String line); /** * Indicates the shell should switch into a lower-level development mode. The exact meaning varies by * shell implementation. * * @param developmentMode true if development mode should be enabled, false otherwise */ void setDevelopmentMode(boolean developmentMode); /** * Displays a progress notification to the user. This notification will ideally be displayed in a * consistent screen location by the shell implementation. * * <p> * An implementation may allow multiple messages to be displayed concurrently. So an implementation can * determine when a flash message replaces a previous flash message, callers should allocate a unique * "slot" name for their messages. It is suggested the class name of the caller be used. This way a * slot will be updated without conflicting with flash message sequences from other slots. * * <p> * Passing an empty string in as the "message" indicates the slot should be cleared. * * <p> * An implementation need not necessarily use the level or slot concepts. They are expected to be * used in most cases, though. * * @param level the importance of the message (cannot be null) * @param message to display (cannot be null, but may be empty) * @param slot the identification slot for the message (cannot be null or empty) */ void flash(Level level, String message, String slot); boolean isDevelopmentMode(); /** * Changes the "path" displayed in the shell prompt. An implementation will ensure this path is * included on the screen, taking care to merge it with the product name and handle any special * formatting requirements (such as ANSI, if supported by the implementation). * * @param path to set (can be null or empty; must NOT be formatted in any special way eg ANSI codes) */ void setPromptPath(String path); void setPromptPath(String path, boolean overrideStyle); /** * Returns the home directory of the current running shell instance * * @return the home directory of the current shell instance */ File getHome(); }
3,694
0.743506
0.742965
101
35.603962
38.758221
114
false
false
0
0
0
0
0
0
0.970297
false
false
0
2e028ed9f89b66ce369f1551868f81e922c3e484
7,258,494,776,280
67b2ae0f386a6a194c6cee136ae4bedb03c4b534
/app/src/main/java/com/ajiew/phonecallapp/ui/MyBadCallItemRecyclerViewAdapter.java
73cb1815520bb9186629af751e6042a811b02b13
[]
no_license
loneyyao/PhoneCall
https://github.com/loneyyao/PhoneCall
cfcd32a70069dc256cdb392a95a2bd4a17561133
514c1ddba211af635edc2c9727a66d51c707da63
refs/heads/master
2022-11-20T16:07:32.659000
2020-07-28T12:33:06
2020-07-28T12:33:06
280,778,246
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ajiew.phonecallapp.ui; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.ajiew.phonecallapp.widget.ItemClickListener; import com.ajiew.phonecallapp.widget.ItemLongClickListener; import com.ajiew.phonecallapp.R; import com.ajiew.phonecallapp.db.CallLog; import java.util.List; public class MyBadCallItemRecyclerViewAdapter extends RecyclerView.Adapter<MyBadCallItemRecyclerViewAdapter.CallLogViewHolder> { private List<CallLog> mValues; private ItemLongClickListener itemLongClickListener; private ItemClickListener itemClickListener; public MyBadCallItemRecyclerViewAdapter() { } public void setmValues(List<CallLog> mValues) { this.mValues = mValues; notifyDataSetChanged(); } @Override public MyBadCallItemRecyclerViewAdapter.CallLogViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.fragment_call_log_list_item, parent, false); return new MyBadCallItemRecyclerViewAdapter.CallLogViewHolder(view); } @Override public void onBindViewHolder(final MyBadCallItemRecyclerViewAdapter.CallLogViewHolder holder, int position) { CallLog callLog = mValues.get(position); String callTime = callLog.getCallTime(); holder.call.setText(callLog.getCall() + " " + (callTime == null ? "" : callTime)); holder.address.setText(callLog.getAddress()); holder.mView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { if (itemLongClickListener != null) { return itemLongClickListener.onLongClickListener(v, holder.getAdapterPosition()); } return false; } }); holder.mView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (itemClickListener != null) { itemClickListener.onItemClick(v, holder.getAdapterPosition()); } } }); } @Override public int getItemCount() { return mValues == null ? 0 : mValues.size(); } public ItemLongClickListener getItemLongClickListener() { return itemLongClickListener; } public void setItemLongClickListener(ItemLongClickListener itemLongClickListener) { this.itemLongClickListener = itemLongClickListener; } public ItemClickListener getItemClickListener() { return itemClickListener; } public void setItemClickListener(ItemClickListener itemClickListener) { this.itemClickListener = itemClickListener; } public static class CallLogViewHolder extends RecyclerView.ViewHolder { public final View mView; public final TextView call; public final TextView address; public CallLogViewHolder(View view) { super(view); mView = view; call = (TextView) view.findViewById(R.id.call); address = (TextView) view.findViewById(R.id.address); } } }
UTF-8
Java
3,321
java
MyBadCallItemRecyclerViewAdapter.java
Java
[]
null
[]
package com.ajiew.phonecallapp.ui; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.ajiew.phonecallapp.widget.ItemClickListener; import com.ajiew.phonecallapp.widget.ItemLongClickListener; import com.ajiew.phonecallapp.R; import com.ajiew.phonecallapp.db.CallLog; import java.util.List; public class MyBadCallItemRecyclerViewAdapter extends RecyclerView.Adapter<MyBadCallItemRecyclerViewAdapter.CallLogViewHolder> { private List<CallLog> mValues; private ItemLongClickListener itemLongClickListener; private ItemClickListener itemClickListener; public MyBadCallItemRecyclerViewAdapter() { } public void setmValues(List<CallLog> mValues) { this.mValues = mValues; notifyDataSetChanged(); } @Override public MyBadCallItemRecyclerViewAdapter.CallLogViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.fragment_call_log_list_item, parent, false); return new MyBadCallItemRecyclerViewAdapter.CallLogViewHolder(view); } @Override public void onBindViewHolder(final MyBadCallItemRecyclerViewAdapter.CallLogViewHolder holder, int position) { CallLog callLog = mValues.get(position); String callTime = callLog.getCallTime(); holder.call.setText(callLog.getCall() + " " + (callTime == null ? "" : callTime)); holder.address.setText(callLog.getAddress()); holder.mView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { if (itemLongClickListener != null) { return itemLongClickListener.onLongClickListener(v, holder.getAdapterPosition()); } return false; } }); holder.mView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (itemClickListener != null) { itemClickListener.onItemClick(v, holder.getAdapterPosition()); } } }); } @Override public int getItemCount() { return mValues == null ? 0 : mValues.size(); } public ItemLongClickListener getItemLongClickListener() { return itemLongClickListener; } public void setItemLongClickListener(ItemLongClickListener itemLongClickListener) { this.itemLongClickListener = itemLongClickListener; } public ItemClickListener getItemClickListener() { return itemClickListener; } public void setItemClickListener(ItemClickListener itemClickListener) { this.itemClickListener = itemClickListener; } public static class CallLogViewHolder extends RecyclerView.ViewHolder { public final View mView; public final TextView call; public final TextView address; public CallLogViewHolder(View view) { super(view); mView = view; call = (TextView) view.findViewById(R.id.call); address = (TextView) view.findViewById(R.id.address); } } }
3,321
0.681722
0.68112
98
32.897961
30.276781
128
false
false
0
0
0
0
0
0
0.459184
false
false
0
723ae764f0792b09e636566157d944ff1a6c87d8
6,992,206,776,722
36ebff17b4e23e77029161b4ad2baf9da5372bd5
/FmsParallelProject/src/main/java/com/flp/fms/service/IFilmService.java
2ca022b2149b1f580578efae03233daefe3f1d03
[]
no_license
kuchuanusha/19May2016Batch
https://github.com/kuchuanusha/19May2016Batch
1c0787c82fc37ad6357b22a6fc758be253161d9c
3db24f1c2893aa4b597adf70dea2efc7346a55d5
refs/heads/master
2021-01-20T19:12:53.095000
2018-01-19T10:26:42
2018-01-19T10:26:42
63,331,542
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.flp.fms.service; import java.text.ParseException; import com.flp.fms.Exceptions.FieldEmptyException; import com.flp.fms.Exceptions.NegativeFieldException; import com.flp.fms.Exceptions.RecordNotFoundException; import com.flp.fms.domain.Film; import java.util.*; public interface IFilmService { String addFilm(Map filmList) throws ParseException, FieldEmptyException, NegativeFieldException; String modifyFilm(Map filmList) throws RecordNotFoundException; boolean removeFilm(int filmId) throws FieldEmptyException, NegativeFieldException, RecordNotFoundException; Film searchFilm(int filmId) throws FieldEmptyException, NegativeFieldException, RecordNotFoundException; List<Film> getAllFilms(); }
UTF-8
Java
745
java
IFilmService.java
Java
[]
null
[]
package com.flp.fms.service; import java.text.ParseException; import com.flp.fms.Exceptions.FieldEmptyException; import com.flp.fms.Exceptions.NegativeFieldException; import com.flp.fms.Exceptions.RecordNotFoundException; import com.flp.fms.domain.Film; import java.util.*; public interface IFilmService { String addFilm(Map filmList) throws ParseException, FieldEmptyException, NegativeFieldException; String modifyFilm(Map filmList) throws RecordNotFoundException; boolean removeFilm(int filmId) throws FieldEmptyException, NegativeFieldException, RecordNotFoundException; Film searchFilm(int filmId) throws FieldEmptyException, NegativeFieldException, RecordNotFoundException; List<Film> getAllFilms(); }
745
0.812081
0.812081
18
39.388889
35.698021
109
false
false
0
0
0
0
0
0
1.277778
false
false
0
52aa55936f3dd2854e6815e1ff0322ebbe0b946e
14,714,557,971,820
315b888dc2175cafb3b670fbbad99a3284e6fdee
/sem2/src/sem2/LinearHash.java
be43044fd337f3a0ed0b507d3f2239207e750e09
[]
no_license
vainyksi/data_structures
https://github.com/vainyksi/data_structures
52ada3b67e17e02cfb187a9328ce0051e22f03f9
19d16a75f0aad1eb82dda6818353e51d83775af9
refs/heads/master
2021-05-29T17:16:02.752000
2015-09-23T05:42:58
2015-09-23T05:42:58
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package sem2; public class LinearHash { }
UTF-8
Java
44
java
LinearHash.java
Java
[]
null
[]
package sem2; public class LinearHash { }
44
0.727273
0.704545
5
7.8
9.907573
25
false
false
0
0
0
0
0
0
0.2
false
false
0
21006dc982aa1e07f62960c4f48f8d01ed66cffa
1,537,598,327,809
4bdb9c70f99cbbc1c55a27a4540b0e590ae61d77
/src/main/java/com/senac/notasaluno/domain/CursaDisciplina.java
fdcb3a3ae020b6a18792758f5997f5a7349d48ad
[]
no_license
lpjunior/SantaLuzia-Manha-2016.3
https://github.com/lpjunior/SantaLuzia-Manha-2016.3
82e7bab242dd5402ebc364d1e45e6dcc2c030168
1da1480657f58b1abfe671b1abe2efacd8815344
refs/heads/master
2021-09-07T08:41:10.969000
2018-02-16T11:14:03
2018-02-16T11:14:03
110,965,072
0
4
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.senac.notasaluno.domain; import javax.persistence.Column; import javax.persistence.EmbeddedId; import javax.persistence.Entity; import org.springframework.beans.factory.annotation.Autowired; @Entity public class CursaDisciplina { /** * A anotação @Autowired - define que o Spring irá gerenciar a instancia do * objeto (new CursaDisciplinaPK()) A anotação @EmbeddedId - Define a origem * da(s) chave(s) primaria(s) do objeto **/ @Autowired @EmbeddedId private CursaDisciplinaPK id; @Column(name = "nota_01", columnDefinition = "float8") private Double nota01; @Column(name = "nota_02", columnDefinition = "float8") private Double nota02; public CursaDisciplina() { } public CursaDisciplina(CursaDisciplinaPK id, Double nota01, Double nota02) { super(); this.id = id; this.nota01 = nota01; this.nota02 = nota02; } public CursaDisciplinaPK getId() { return id; } public void setId(CursaDisciplinaPK id) { this.id = id; } public Double getNota01() { return nota01; } public void setNota01(Double nota01) { this.nota01 = nota01; } public Double getNota02() { return nota02; } public void setNota02(Double nota02) { this.nota02 = nota02; } public Double getMedia() { return (nota01 + nota02) / 2; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CursaDisciplina other = (CursaDisciplina) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } }
UTF-8
Java
1,890
java
CursaDisciplina.java
Java
[]
null
[]
package com.senac.notasaluno.domain; import javax.persistence.Column; import javax.persistence.EmbeddedId; import javax.persistence.Entity; import org.springframework.beans.factory.annotation.Autowired; @Entity public class CursaDisciplina { /** * A anotação @Autowired - define que o Spring irá gerenciar a instancia do * objeto (new CursaDisciplinaPK()) A anotação @EmbeddedId - Define a origem * da(s) chave(s) primaria(s) do objeto **/ @Autowired @EmbeddedId private CursaDisciplinaPK id; @Column(name = "nota_01", columnDefinition = "float8") private Double nota01; @Column(name = "nota_02", columnDefinition = "float8") private Double nota02; public CursaDisciplina() { } public CursaDisciplina(CursaDisciplinaPK id, Double nota01, Double nota02) { super(); this.id = id; this.nota01 = nota01; this.nota02 = nota02; } public CursaDisciplinaPK getId() { return id; } public void setId(CursaDisciplinaPK id) { this.id = id; } public Double getNota01() { return nota01; } public void setNota01(Double nota01) { this.nota01 = nota01; } public Double getNota02() { return nota02; } public void setNota02(Double nota02) { this.nota02 = nota02; } public Double getMedia() { return (nota01 + nota02) / 2; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CursaDisciplina other = (CursaDisciplina) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } }
1,890
0.651989
0.622812
89
19.179775
19.106186
77
false
false
0
0
0
0
0
0
1.494382
false
false
0
f8de7265e2678ce1797d69d1da4c71846233273e
32,049,045,976,454
8c30768ebcecc1518baf4ea29909cf168a6009ee
/src/main/java/pl/joegreen/lambdaFromString/classFactory/DefaultClassFactory.java
6bbed6359f8060e30de9ab1878fbb123f844716e
[ "MIT" ]
permissive
jbax/lambdaFromString
https://github.com/jbax/lambdaFromString
acc2564dede363116b666560f1326d3f6204d340
d7c9770066e08f9065460e89a5f15729ce281656
refs/heads/master
2021-01-12T14:01:45.351000
2015-09-16T21:41:39
2015-09-16T21:41:39
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package pl.joegreen.lambdaFromString.classFactory; import javax.tools.DiagnosticCollector; import javax.tools.JavaCompiler; import javax.tools.JavaFileObject; import javax.tools.ToolProvider; import java.util.Collections; import java.util.Map; public class DefaultClassFactory implements ClassFactory { @Override public Class<?> createClass(String fullClassName, String sourceCode) throws ClassCompilationException { try { JavaCompiler compiler = findJavaCompiler(); Map<String, CompiledClassJavaObject> compiledClassesBytes = compileClasses(compiler, fullClassName, sourceCode); return loadClass(fullClassName, compiledClassesBytes); } catch (ClassNotFoundException | CannotFindJavaCompilerException | RuntimeException e) { throw new ClassCompilationException(e); } } protected Class<?> loadClass(String fullClassName, Map<String, CompiledClassJavaObject> compiledClassesBytes) throws ClassNotFoundException { return (new InMemoryClassLoader(compiledClassesBytes)).loadClass(fullClassName); } protected Map<String, CompiledClassJavaObject> compileClasses(JavaCompiler compiler, String fullClassName, String sourceCode) throws ClassCompilationException { ClassSourceJavaObject classSourceObject = new ClassSourceJavaObject(fullClassName, sourceCode); Map<String, CompiledClassJavaObject> compiledClassesBytes; /* * diagnosticListener = null -> compiler's default reporting * diagnostics; locale = null -> default locale to format diagnostics; * charset = null -> uses platform default charset */ try (InMemoryFileManager stdFileManager = new InMemoryFileManager(compiler.getStandardFileManager(null, null, null))) { DiagnosticCollector<JavaFileObject> diagnosticsCollector = new DiagnosticCollector<>(); JavaCompiler.CompilationTask compilationTask = compiler.getTask(null, stdFileManager, diagnosticsCollector, Collections.emptyList(), null, Collections.singletonList(classSourceObject)); boolean status = compilationTask.call(); if (!status) { throw new ClassCompilationException(new CompilationDetails(fullClassName, sourceCode, diagnosticsCollector.getDiagnostics())); } return stdFileManager.getClasses(); } } private JavaCompiler findJavaCompiler() throws CannotFindJavaCompilerException { JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); if (compiler == null) { throw new CannotFindJavaCompilerException(); } return compiler; } private static class CannotFindJavaCompilerException extends Exception { CannotFindJavaCompilerException() { super("ToolProvider.getSystemJavaCompiler() returned null - please check your JDK version and/or tools.jar availability."); } } }
UTF-8
Java
2,986
java
DefaultClassFactory.java
Java
[]
null
[]
package pl.joegreen.lambdaFromString.classFactory; import javax.tools.DiagnosticCollector; import javax.tools.JavaCompiler; import javax.tools.JavaFileObject; import javax.tools.ToolProvider; import java.util.Collections; import java.util.Map; public class DefaultClassFactory implements ClassFactory { @Override public Class<?> createClass(String fullClassName, String sourceCode) throws ClassCompilationException { try { JavaCompiler compiler = findJavaCompiler(); Map<String, CompiledClassJavaObject> compiledClassesBytes = compileClasses(compiler, fullClassName, sourceCode); return loadClass(fullClassName, compiledClassesBytes); } catch (ClassNotFoundException | CannotFindJavaCompilerException | RuntimeException e) { throw new ClassCompilationException(e); } } protected Class<?> loadClass(String fullClassName, Map<String, CompiledClassJavaObject> compiledClassesBytes) throws ClassNotFoundException { return (new InMemoryClassLoader(compiledClassesBytes)).loadClass(fullClassName); } protected Map<String, CompiledClassJavaObject> compileClasses(JavaCompiler compiler, String fullClassName, String sourceCode) throws ClassCompilationException { ClassSourceJavaObject classSourceObject = new ClassSourceJavaObject(fullClassName, sourceCode); Map<String, CompiledClassJavaObject> compiledClassesBytes; /* * diagnosticListener = null -> compiler's default reporting * diagnostics; locale = null -> default locale to format diagnostics; * charset = null -> uses platform default charset */ try (InMemoryFileManager stdFileManager = new InMemoryFileManager(compiler.getStandardFileManager(null, null, null))) { DiagnosticCollector<JavaFileObject> diagnosticsCollector = new DiagnosticCollector<>(); JavaCompiler.CompilationTask compilationTask = compiler.getTask(null, stdFileManager, diagnosticsCollector, Collections.emptyList(), null, Collections.singletonList(classSourceObject)); boolean status = compilationTask.call(); if (!status) { throw new ClassCompilationException(new CompilationDetails(fullClassName, sourceCode, diagnosticsCollector.getDiagnostics())); } return stdFileManager.getClasses(); } } private JavaCompiler findJavaCompiler() throws CannotFindJavaCompilerException { JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); if (compiler == null) { throw new CannotFindJavaCompilerException(); } return compiler; } private static class CannotFindJavaCompilerException extends Exception { CannotFindJavaCompilerException() { super("ToolProvider.getSystemJavaCompiler() returned null - please check your JDK version and/or tools.jar availability."); } } }
2,986
0.723376
0.723376
62
47.129032
43.631699
164
false
false
0
0
0
0
0
0
0.870968
false
false
0
f90299b48bd041aa5940e06c0ce85fe95c82208d
32,049,045,976,455
0f85573aa83000e32b933d5522eb91f97cdd103d
/logback-android/src/main/java/ch/qos/logback/core/net/SSLSocketAppenderBase.java
f4d9dff8c399fb34decc1a1712b64752792879fd
[ "Apache-2.0" ]
permissive
tony19/logback-android
https://github.com/tony19/logback-android
93526d94d5ec30a1290c87c03da257b7ecfd854b
d6ed2017fb87e30e8b32d794523ac29c24123c87
refs/heads/main
2023-08-27T17:06:39.694000
2023-06-16T02:04:49
2023-06-16T02:04:49
1,970,932
1,011
149
Apache-2.0
false
2023-08-27T16:54:15
2011-06-29T06:47:06
2023-08-26T15:01:23
2023-08-27T16:54:04
69,960
1,112
162
25
Java
false
false
/** * Copyright 2019 Anthony Trinh * * 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 ch.qos.logback.core.net; import javax.net.SocketFactory; import javax.net.ssl.SSLContext; import ch.qos.logback.core.net.ssl.ConfigurableSSLSocketFactory; import ch.qos.logback.core.net.ssl.SSLComponent; import ch.qos.logback.core.net.ssl.SSLConfiguration; import ch.qos.logback.core.net.ssl.SSLParametersConfiguration; /** * * This is the base class for module specific SSLSocketAppender implementations. * * @author Carl Harris */ public abstract class SSLSocketAppenderBase<E> extends AbstractSocketAppender<E> implements SSLComponent { private SSLConfiguration ssl; private SocketFactory socketFactory; /** * Gets an {@link SocketFactory} that produces SSL sockets using an * {@link SSLContext} that is derived from the appender's configuration. * @return socket factory */ @Override protected SocketFactory getSocketFactory() { return socketFactory; } /** * {@inheritDoc} */ @Override public void start() { try { SSLContext sslContext = getSsl().createContext(this); SSLParametersConfiguration parameters = getSsl().getParameters(); parameters.setContext(getContext()); socketFactory = new ConfigurableSSLSocketFactory(parameters, sslContext.getSocketFactory()); super.start(); } catch (Exception ex) { addError(ex.getMessage(), ex); } } /** * Gets the SSL configuration. * @return SSL configuration; if no configuration has been set, a * default configuration is returned */ public SSLConfiguration getSsl() { if (ssl == null) { ssl = new SSLConfiguration(); } return ssl; } /** * Sets the SSL configuration. * @param ssl the SSL configuration to set */ public void setSsl(SSLConfiguration ssl) { this.ssl = ssl; } }
UTF-8
Java
2,408
java
SSLSocketAppenderBase.java
Java
[ { "context": "/**\n * Copyright 2019 Anthony Trinh\n *\n * Licensed under the Apache License, Version ", "end": 35, "score": 0.9998689889907837, "start": 22, "tag": "NAME", "value": "Anthony Trinh" }, { "context": "c SSLSocketAppender implementations.\n *\n * @author Carl Harris\n */...
null
[]
/** * Copyright 2019 <NAME> * * 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 ch.qos.logback.core.net; import javax.net.SocketFactory; import javax.net.ssl.SSLContext; import ch.qos.logback.core.net.ssl.ConfigurableSSLSocketFactory; import ch.qos.logback.core.net.ssl.SSLComponent; import ch.qos.logback.core.net.ssl.SSLConfiguration; import ch.qos.logback.core.net.ssl.SSLParametersConfiguration; /** * * This is the base class for module specific SSLSocketAppender implementations. * * @author <NAME> */ public abstract class SSLSocketAppenderBase<E> extends AbstractSocketAppender<E> implements SSLComponent { private SSLConfiguration ssl; private SocketFactory socketFactory; /** * Gets an {@link SocketFactory} that produces SSL sockets using an * {@link SSLContext} that is derived from the appender's configuration. * @return socket factory */ @Override protected SocketFactory getSocketFactory() { return socketFactory; } /** * {@inheritDoc} */ @Override public void start() { try { SSLContext sslContext = getSsl().createContext(this); SSLParametersConfiguration parameters = getSsl().getParameters(); parameters.setContext(getContext()); socketFactory = new ConfigurableSSLSocketFactory(parameters, sslContext.getSocketFactory()); super.start(); } catch (Exception ex) { addError(ex.getMessage(), ex); } } /** * Gets the SSL configuration. * @return SSL configuration; if no configuration has been set, a * default configuration is returned */ public SSLConfiguration getSsl() { if (ssl == null) { ssl = new SSLConfiguration(); } return ssl; } /** * Sets the SSL configuration. * @param ssl the SSL configuration to set */ public void setSsl(SSLConfiguration ssl) { this.ssl = ssl; } }
2,396
0.708056
0.704734
86
27
25.158104
80
false
false
0
0
0
0
0
0
0.325581
false
false
0
a4e1e9aa18642e7fb908edac137076e9ca02a657
30,648,886,684,806
fb3a683580fbe0d3c23bfd8199e0b41a34e46e10
/app/src/main/java/com/breakingsword/mine/mine/MineContract.java
e19acb2761dfb3a9a114857ac08274d14c082e4a
[]
no_license
breakingsword/Mine
https://github.com/breakingsword/Mine
6fd818b8e9e4a3967ea6f298122210720d56d990
be5ba010bc9c1da46bd296bf526336b82e67ce4a
refs/heads/master
2020-03-29T18:05:49.096000
2018-10-24T08:48:24
2018-10-24T08:48:24
150,194,356
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.breakingsword.mine.mine; import com.breakingsword.mine.BasePresenter; import com.breakingsword.mine.BaseView; import com.breakingsword.mine.model.bean.Reward; import java.util.List; public interface MineContract { interface MineView extends BaseView<MinePresenter> { void refreshView(); } interface MinePresenter extends BasePresenter { List<Reward> getRewardList(); int getLevel(); int getExp(); void deleteReward(Reward reward); void completeOnePotato(); } }
UTF-8
Java
541
java
MineContract.java
Java
[]
null
[]
package com.breakingsword.mine.mine; import com.breakingsword.mine.BasePresenter; import com.breakingsword.mine.BaseView; import com.breakingsword.mine.model.bean.Reward; import java.util.List; public interface MineContract { interface MineView extends BaseView<MinePresenter> { void refreshView(); } interface MinePresenter extends BasePresenter { List<Reward> getRewardList(); int getLevel(); int getExp(); void deleteReward(Reward reward); void completeOnePotato(); } }
541
0.709797
0.709797
21
24.761906
18.582903
56
false
false
0
0
0
0
0
0
0.52381
false
false
0
2167cf98b7757f88798d21e3c68c94220c52766e
5,884,105,256,122
15b260ccada93e20bb696ae19b14ec62e78ed023
/v2/src/main/java/com/alipay/api/response/AlipayOpenMiniQrcodeQueryResponse.java
47d4ae8170771d30c31a9f65f8be8cb39237c1c5
[ "Apache-2.0" ]
permissive
alipay/alipay-sdk-java-all
https://github.com/alipay/alipay-sdk-java-all
df461d00ead2be06d834c37ab1befa110736b5ab
8cd1750da98ce62dbc931ed437f6101684fbb66a
refs/heads/master
2023-08-27T03:59:06.566000
2023-08-22T14:54:57
2023-08-22T14:54:57
132,569,986
470
207
Apache-2.0
false
2022-12-25T07:37:40
2018-05-08T07:19:22
2022-12-17T09:20:53
2022-12-25T07:37:39
344,790
385
180
46
Java
false
false
package com.alipay.api.response; import java.util.List; import com.alipay.api.internal.mapping.ApiField; import com.alipay.api.internal.mapping.ApiListField; import com.alipay.api.domain.QrCodeRouteGroup; import com.alipay.api.AlipayResponse; /** * ALIPAY API: alipay.open.mini.qrcode.query response. * * @author auto create * @since 1.0, 2023-05-31 19:18:11 */ public class AlipayOpenMiniQrcodeQueryResponse extends AlipayResponse { private static final long serialVersionUID = 3525397362686298363L; /** * 规则路由数据列表 */ @ApiListField("qr_code_route_groups") @ApiField("qr_code_route_group") private List<QrCodeRouteGroup> qrCodeRouteGroups; /** * 数据总数 */ @ApiField("total_items") private Long totalItems; public void setQrCodeRouteGroups(List<QrCodeRouteGroup> qrCodeRouteGroups) { this.qrCodeRouteGroups = qrCodeRouteGroups; } public List<QrCodeRouteGroup> getQrCodeRouteGroups( ) { return this.qrCodeRouteGroups; } public void setTotalItems(Long totalItems) { this.totalItems = totalItems; } public Long getTotalItems( ) { return this.totalItems; } }
UTF-8
Java
1,125
java
AlipayOpenMiniQrcodeQueryResponse.java
Java
[ { "context": "ay.open.mini.qrcode.query response.\n * \n * @author auto create\n * @since 1.0, 2023-05-31 19:18:11\n */\npublic cla", "end": 331, "score": 0.7721385359764099, "start": 320, "tag": "USERNAME", "value": "auto create" } ]
null
[]
package com.alipay.api.response; import java.util.List; import com.alipay.api.internal.mapping.ApiField; import com.alipay.api.internal.mapping.ApiListField; import com.alipay.api.domain.QrCodeRouteGroup; import com.alipay.api.AlipayResponse; /** * ALIPAY API: alipay.open.mini.qrcode.query response. * * @author auto create * @since 1.0, 2023-05-31 19:18:11 */ public class AlipayOpenMiniQrcodeQueryResponse extends AlipayResponse { private static final long serialVersionUID = 3525397362686298363L; /** * 规则路由数据列表 */ @ApiListField("qr_code_route_groups") @ApiField("qr_code_route_group") private List<QrCodeRouteGroup> qrCodeRouteGroups; /** * 数据总数 */ @ApiField("total_items") private Long totalItems; public void setQrCodeRouteGroups(List<QrCodeRouteGroup> qrCodeRouteGroups) { this.qrCodeRouteGroups = qrCodeRouteGroups; } public List<QrCodeRouteGroup> getQrCodeRouteGroups( ) { return this.qrCodeRouteGroups; } public void setTotalItems(Long totalItems) { this.totalItems = totalItems; } public Long getTotalItems( ) { return this.totalItems; } }
1,125
0.758401
0.726612
47
22.425531
22.480957
77
false
false
0
0
0
0
0
0
0.893617
false
false
0
809d0a2a5a622a0d7482dfa3e89dc6b73bc5cf37
24,051,816,895,302
97dd9c69bf7540667840177660b02cee8c758046
/FTC/Autonomous/eashantest2.java
37576246f6ee27cc9a57dab91076380e9554bbd1
[]
no_license
eashansingh905/Robotics_2017_18
https://github.com/eashansingh905/Robotics_2017_18
9efebdc27c5cd0e2ea11f8a61d8d0556408b9a2e
ad53695429ddffe9b8876eb188130e402a10df4a
refs/heads/master
2021-09-14T21:59:27.794000
2018-05-20T20:21:29
2018-05-20T20:21:29
118,385,079
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.firstinspires.ftc.teamcode.Autonomous; import com.qualcomm.robotcore.eventloop.opmode.Autonomous; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.util.ElapsedTime; import org.firstinspires.ftc.teamcode.Autonomous.Methods.Camera; import org.firstinspires.ftc.teamcode.Autonomous.Methods.Drivetrain; import org.firstinspires.ftc.teamcode.Autonomous.Methods.GlyphMechanism; import org.firstinspires.ftc.teamcode.Autonomous.Methods.JewelMechanism; /** * * Created by Eashan on 11/30/2017. */ @Autonomous (name = " Eashan Test Left Turn", group = "Red Alliance") public class eashantest2 extends LinearOpMode { Camera camera = new Camera(telemetry); JewelMechanism jewelMechanism = new JewelMechanism(); GlyphMechanism glyphMechanism = new GlyphMechanism(); Drivetrain drivetrain = new Drivetrain(); ElapsedTime time = new ElapsedTime(); int[][] encoderValues = new int[6][2]; @Override public void runOpMode() throws InterruptedException { drivetrain.init(hardwareMap); glyphMechanism.init(hardwareMap); jewelMechanism.init(hardwareMap); camera.init(hardwareMap); waitForStart(); //read pictograph String key = camera.getKey(); camera.cameraOff(); //hold onto glyph glyphMechanism.closeTop(); glyphMechanism.closeBottom(); sleep(1000); //so that it can finish closing before it goes up glyphMechanism.up(); jewelMechanism.rotateArm(0.45); //lower servo arm //make sure jewel arm is in the center jewelMechanism.lowerArm(); sleep(100); //turn on light jewelMechanism.ledOn(); //read color jewelMechanism.colorRed(); //true = red, false = blue //turn to knock off jewel using servo arm if (jewelMechanism.colorRed() == true) { jewelMechanism.rotateArm(0.9); sleep(1000); //turn off light jewelMechanism.ledOff(); jewelMechanism.rotateArm(0.45); //raise servo arm jewelMechanism.raiseArm(); sleep(1000); } else { jewelMechanism.rotateArm(0.1); sleep(1000); //turn off light jewelMechanism.ledOff(); jewelMechanism.rotateArm(0.45); //raise servo arm jewelMechanism.raiseArm(); sleep(1000); } //drives to cryptobox //strafe x feet based on pictograph column if (key == "RIGHT") { drivetrain.drive(1, 0.3, encoderValues[0]); drivetrain.diagonalLeft(1, 0.5); glyphMechanism.wedge(); drivetrain.drive(-0.25, 1); glyphMechanism.openBottom(); glyphMechanism.openTop(); //drivetrain.drive(0.5, 0.7); //drivetrain.drive(-0.3, 1); } else if (key == "CENTER") { drivetrain.drive(1, 0.3, encoderValues[0]); drivetrain.strafe(-.45, 1); // -0.4 drivetrain.diagonalLeft(1, 0.5); glyphMechanism.wedge(); drivetrain.drive(-0.25, 1); glyphMechanism.openBottom(); glyphMechanism.openTop(); } else if (key == "LEFT") { drivetrain.drive(1, 0.3, encoderValues[0]); drivetrain.strafe(-.75, 1); drivetrain.diagonalLeft(1, 0.5); glyphMechanism.wedge(); drivetrain.drive(-0.3, 1); glyphMechanism.openBottom(); glyphMechanism.openTop(); //glyphMechanism.openBottom(); //drivetrain.drive(0.5, 0.7); //drivetrain.drive(-0.3, 1); } else { drivetrain.drive(1, 0.3, encoderValues[0]); drivetrain.strafe(-.45, 1); // -0.4 drivetrain.diagonalLeft(1, 0.5); glyphMechanism.wedge(); drivetrain.drive(-0.25, 1); glyphMechanism.openBottom(); glyphMechanism.openTop(); //10drivetrain.drive(0.5, 0.7); //drivetrain.drive(-0.3, 1); /* //release glyph drivetrain.turnWithEncoder(36,0.5, encoderValues[2]); //glyphMechanism.openBottom(); glyphMechanism.down(); glyphMechanism.openBottom(); drivetrain.turnWithEncoder(-36,0.5, encoderValues[3]); drivetrain.strafe(-0.1,0.2); drivetrain.drive(0.6,1, encoderValues[4]); drivetrain.drive(-0.3,1, encoderValues[5]); glyphMechanism.down(); // glyphMechanism.openTop(); //push glyph into cryptobox //drivetrain.drive(.5, 1); //drivetrain.drive(-.2, 1); while (true) { telemetry.update(); telemetry.addData("hi", 5); for (int a = 0; a < 6; a++) { for (int b = 0; b < 2; b++) { telemetry.addData(""+a + " " + b, encoderValues[a][b]); } } */ } } }
UTF-8
Java
5,238
java
eashantest2.java
Java
[ { "context": "ethods.JewelMechanism;\r\n\r\n\r\n/**\r\n *\r\n * Created by Eashan on 11/30/2017.\r\n */\r\n@Autonomous (name = \" Eashan", "end": 544, "score": 0.9996585845947266, "start": 538, "tag": "NAME", "value": "Eashan" } ]
null
[]
package org.firstinspires.ftc.teamcode.Autonomous; import com.qualcomm.robotcore.eventloop.opmode.Autonomous; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.util.ElapsedTime; import org.firstinspires.ftc.teamcode.Autonomous.Methods.Camera; import org.firstinspires.ftc.teamcode.Autonomous.Methods.Drivetrain; import org.firstinspires.ftc.teamcode.Autonomous.Methods.GlyphMechanism; import org.firstinspires.ftc.teamcode.Autonomous.Methods.JewelMechanism; /** * * Created by Eashan on 11/30/2017. */ @Autonomous (name = " Eashan Test Left Turn", group = "Red Alliance") public class eashantest2 extends LinearOpMode { Camera camera = new Camera(telemetry); JewelMechanism jewelMechanism = new JewelMechanism(); GlyphMechanism glyphMechanism = new GlyphMechanism(); Drivetrain drivetrain = new Drivetrain(); ElapsedTime time = new ElapsedTime(); int[][] encoderValues = new int[6][2]; @Override public void runOpMode() throws InterruptedException { drivetrain.init(hardwareMap); glyphMechanism.init(hardwareMap); jewelMechanism.init(hardwareMap); camera.init(hardwareMap); waitForStart(); //read pictograph String key = camera.getKey(); camera.cameraOff(); //hold onto glyph glyphMechanism.closeTop(); glyphMechanism.closeBottom(); sleep(1000); //so that it can finish closing before it goes up glyphMechanism.up(); jewelMechanism.rotateArm(0.45); //lower servo arm //make sure jewel arm is in the center jewelMechanism.lowerArm(); sleep(100); //turn on light jewelMechanism.ledOn(); //read color jewelMechanism.colorRed(); //true = red, false = blue //turn to knock off jewel using servo arm if (jewelMechanism.colorRed() == true) { jewelMechanism.rotateArm(0.9); sleep(1000); //turn off light jewelMechanism.ledOff(); jewelMechanism.rotateArm(0.45); //raise servo arm jewelMechanism.raiseArm(); sleep(1000); } else { jewelMechanism.rotateArm(0.1); sleep(1000); //turn off light jewelMechanism.ledOff(); jewelMechanism.rotateArm(0.45); //raise servo arm jewelMechanism.raiseArm(); sleep(1000); } //drives to cryptobox //strafe x feet based on pictograph column if (key == "RIGHT") { drivetrain.drive(1, 0.3, encoderValues[0]); drivetrain.diagonalLeft(1, 0.5); glyphMechanism.wedge(); drivetrain.drive(-0.25, 1); glyphMechanism.openBottom(); glyphMechanism.openTop(); //drivetrain.drive(0.5, 0.7); //drivetrain.drive(-0.3, 1); } else if (key == "CENTER") { drivetrain.drive(1, 0.3, encoderValues[0]); drivetrain.strafe(-.45, 1); // -0.4 drivetrain.diagonalLeft(1, 0.5); glyphMechanism.wedge(); drivetrain.drive(-0.25, 1); glyphMechanism.openBottom(); glyphMechanism.openTop(); } else if (key == "LEFT") { drivetrain.drive(1, 0.3, encoderValues[0]); drivetrain.strafe(-.75, 1); drivetrain.diagonalLeft(1, 0.5); glyphMechanism.wedge(); drivetrain.drive(-0.3, 1); glyphMechanism.openBottom(); glyphMechanism.openTop(); //glyphMechanism.openBottom(); //drivetrain.drive(0.5, 0.7); //drivetrain.drive(-0.3, 1); } else { drivetrain.drive(1, 0.3, encoderValues[0]); drivetrain.strafe(-.45, 1); // -0.4 drivetrain.diagonalLeft(1, 0.5); glyphMechanism.wedge(); drivetrain.drive(-0.25, 1); glyphMechanism.openBottom(); glyphMechanism.openTop(); //10drivetrain.drive(0.5, 0.7); //drivetrain.drive(-0.3, 1); /* //release glyph drivetrain.turnWithEncoder(36,0.5, encoderValues[2]); //glyphMechanism.openBottom(); glyphMechanism.down(); glyphMechanism.openBottom(); drivetrain.turnWithEncoder(-36,0.5, encoderValues[3]); drivetrain.strafe(-0.1,0.2); drivetrain.drive(0.6,1, encoderValues[4]); drivetrain.drive(-0.3,1, encoderValues[5]); glyphMechanism.down(); // glyphMechanism.openTop(); //push glyph into cryptobox //drivetrain.drive(.5, 1); //drivetrain.drive(-.2, 1); while (true) { telemetry.update(); telemetry.addData("hi", 5); for (int a = 0; a < 6; a++) { for (int b = 0; b < 2; b++) { telemetry.addData(""+a + " " + b, encoderValues[a][b]); } } */ } } }
5,238
0.553074
0.5231
157
31.363058
19.320347
75
false
false
0
0
0
0
0
0
0.859873
false
false
0
ce23eca73c0cc237ecbd5facfa908c8abe877d6d
18,726,057,425,205
b2d511ddbcf00140a87c7afe6fac9640502bd1e3
/application/model/src/main/java/by/vbalanse/model/common/AbstractCompositeKeyEntity_.java
2f3109aea4f6dc32fb4f1943907e03d112c53534
[]
no_license
vasilinka/vbalanse
https://github.com/vasilinka/vbalanse
b6b9296ad78a2eeed02262b908beef98591438d2
a33c17c8a249b9b8ad6c3f55fdc84a5a5dd6d9ec
refs/heads/master
2021-09-03T04:39:03.478000
2018-01-05T16:26:29
2018-01-05T16:26:29
114,117,396
0
2
null
false
2017-12-29T08:07:38
2017-12-13T12:21:35
2017-12-13T12:56:37
2017-12-29T08:07:38
13,644
0
2
0
JavaScript
false
null
package by.vbalanse.model.common; import javax.annotation.Generated; import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.StaticMetamodel; @Generated(value="EclipseLink-2.2.0.v20110202-r8913", date="2014-08-12T19:39:08") @StaticMetamodel(AbstractCompositeKeyEntity.class) public abstract class AbstractCompositeKeyEntity_ extends AbstractEntity_ { public static volatile SingularAttribute<AbstractCompositeKeyEntity, ? extends Object> id; }
UTF-8
Java
484
java
AbstractCompositeKeyEntity_.java
Java
[]
null
[]
package by.vbalanse.model.common; import javax.annotation.Generated; import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.StaticMetamodel; @Generated(value="EclipseLink-2.2.0.v20110202-r8913", date="2014-08-12T19:39:08") @StaticMetamodel(AbstractCompositeKeyEntity.class) public abstract class AbstractCompositeKeyEntity_ extends AbstractEntity_ { public static volatile SingularAttribute<AbstractCompositeKeyEntity, ? extends Object> id; }
484
0.832645
0.772727
13
36.307693
32.864254
94
false
false
0
0
0
0
0
0
0.538462
false
false
0
41e0375701512f9bac59ea830bc36354f4795745
20,547,123,561,803
47f4a7279bc46b09f29c2a89006103e1c503ca8a
/src/com/java/bohomolov/abstractions/StoolOnWheels.java
924921dbd97746f01605180e67af2980c209c1fd
[]
no_license
Fllemeth/Javalab
https://github.com/Fllemeth/Javalab
6b59b708197ad053b43f2d07c4f20fc9060cb6de
6d3b9f48d5a761f95576412e6b9a426a9197891e
refs/heads/master
2023-02-07T00:25:04.192000
2020-12-17T20:43:26
2020-12-17T20:43:26
322,405,289
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.java.bohomolov.abstractions; import com.java.bohomolov.accessories.ChairSeat; import com.java.bohomolov.accessories.ChairWheel; import com.java.bohomolov.enums.Style; import java.util.List; public abstract class StoolOnWheels extends Stool { protected StoolOnWheels(int height, Style style, ChairSeat chairSeat, List<ChairWheel> legList) { super(height, style, chairSeat, legList); } public String toString() { return super.toString(); } public List<ChairWheel> getLegList() { return (List<ChairWheel>) super.getLegList(); } }
UTF-8
Java
594
java
StoolOnWheels.java
Java
[]
null
[]
package com.java.bohomolov.abstractions; import com.java.bohomolov.accessories.ChairSeat; import com.java.bohomolov.accessories.ChairWheel; import com.java.bohomolov.enums.Style; import java.util.List; public abstract class StoolOnWheels extends Stool { protected StoolOnWheels(int height, Style style, ChairSeat chairSeat, List<ChairWheel> legList) { super(height, style, chairSeat, legList); } public String toString() { return super.toString(); } public List<ChairWheel> getLegList() { return (List<ChairWheel>) super.getLegList(); } }
594
0.723906
0.723906
23
24.826086
26.237465
101
false
false
0
0
0
0
0
0
0.608696
false
false
0
48e46ce4a8e1a261492b682ea11c630f34672a62
1,065,151,903,089
6b9b06355eccf85c4e81a3d28bab93b0a5eab658
/src/studentmanagementbackend/Contact.java
fc3ae52f2403af82be6a25f64d45f66158292f32
[]
no_license
zhuang002/kevin-studentmanageback
https://github.com/zhuang002/kevin-studentmanageback
06c8af3f3ecdc572d4e9aeec58ce479ee0411138
dda9e03b8c6d077656bbb240e3ce8a029e085f26
refs/heads/master
2023-02-13T19:09:13.627000
2021-01-09T19:59:51
2021-01-09T19:59:51
272,072,268
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package studentmanagementbackend; import java.io.Serializable; /** * * @author zhuan */ public class Contact implements Serializable{ String homephone; String cellphone; String email; public void setHomephone(String homephone) { this.homephone = homephone; } public void setCellphone(String cellphone) { this.cellphone = cellphone; } public void setEmail(String email) { this.email = email; } public String getHomephone() { return homephone; } public String getCellphone() { return cellphone; } public String getEmail() { return email; } }
UTF-8
Java
844
java
Contact.java
Java
[ { "context": ";\n\nimport java.io.Serializable;\n\n/**\n *\n * @author zhuan\n */\npublic class Contact implements Serializable{", "end": 273, "score": 0.9993738532066345, "start": 268, "tag": "USERNAME", "value": "zhuan" } ]
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package studentmanagementbackend; import java.io.Serializable; /** * * @author zhuan */ public class Contact implements Serializable{ String homephone; String cellphone; String email; public void setHomephone(String homephone) { this.homephone = homephone; } public void setCellphone(String cellphone) { this.cellphone = cellphone; } public void setEmail(String email) { this.email = email; } public String getHomephone() { return homephone; } public String getCellphone() { return cellphone; } public String getEmail() { return email; } }
844
0.656398
0.656398
42
19.095238
19.209137
79
false
false
0
0
0
0
0
0
0.333333
false
false
0
39ba3f32f68220a40142d0ac7297a5461940c64d
15,221,364,112,862
715524f10f964a81cbf283aa578bf30457bd261d
/src/net/cox/augies/school/apcsa/fall/one/Alpha.java
ad2ec4d73d307454d7e470d1f1a6f45d2b9c87f7
[]
no_license
Augies/APCSA
https://github.com/Augies/APCSA
b046354ee854b41c319b828fa257ba659f9f0514
3f8c9bc3904e5ee862283392f65efd0a9622ebed
refs/heads/master
2020-07-05T06:36:39.910000
2020-01-23T15:09:07
2020-01-23T15:09:07
202,556,392
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package net.cox.augies.school.apcsa.fall.one; import java.util.Scanner; /** * Use a for loop and integer of 65, print alphabet to the screen by adding one * to integer then casting it to a char, and printing it * * @author augies * */ public class Alpha { static Scanner scln = new Scanner(System.in); static int start; public static void main(String[] args) { System.out.println("Lower case or Upper case? (L/U)"); String answer = scln.nextLine().toUpperCase(); if (answer.equals("U")) { start = 65;// start of upper case } else { start = 97;// start of lower case } for (int i = start; i < start + 26; i++) { System.out.print((char) i); } } }
UTF-8
Java
682
java
Alpha.java
Java
[ { "context": "sting it to a char, and printing it\n * \n * @author augies\n *\n */\npublic class Alpha {\n\tstatic Scanner scln ", "end": 236, "score": 0.9988785982131958, "start": 230, "tag": "USERNAME", "value": "augies" } ]
null
[]
package net.cox.augies.school.apcsa.fall.one; import java.util.Scanner; /** * Use a for loop and integer of 65, print alphabet to the screen by adding one * to integer then casting it to a char, and printing it * * @author augies * */ public class Alpha { static Scanner scln = new Scanner(System.in); static int start; public static void main(String[] args) { System.out.println("Lower case or Upper case? (L/U)"); String answer = scln.nextLine().toUpperCase(); if (answer.equals("U")) { start = 65;// start of upper case } else { start = 97;// start of lower case } for (int i = start; i < start + 26; i++) { System.out.print((char) i); } } }
682
0.652493
0.640762
28
23.357143
21.804676
79
false
false
0
0
0
0
0
0
1.428571
false
false
0
32a52551628271f1e6d571f0225d000cdd79bcd6
23,974,507,511,859
515105d8880f4f11fac1f7267cca6b874a13c957
/src/homeworks/Homework07.java
99c339f0cf8fb8fd3c0bf8d1054cc115fdc805e9
[]
no_license
RobertSabadosh/Projects
https://github.com/RobertSabadosh/Projects
ecdfeec890f47f0097a1cccd5ec5c8835d247fb2
6fd7413c955db0c94836e579430ff9f7ea5fe605
refs/heads/master
2022-12-13T02:25:03.411000
2020-09-09T18:15:50
2020-09-09T18:15:50
276,674,521
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package homeworks; public class Homework07 { public static void main(String[] args) { System.out.println(heroChoice("left")); System.out.println(heroChoice("right")); System.out.println(heroChoice("straight")); split(); int speed = 129; split(); System.out.println(speedLimit2(46)); System.out.println(speedLimit2(56)); System.out.println(speedLimit2(80)); System.out.println(speedLimit2(120)); split(); System.out.println(heroChoice2(1)); System.out.println(heroChoice2(2)); System.out.println(heroChoice2(3)); System.out.println(heroChoice2(4)); split(); } public static String heroChoice(String way) { String path = ""; switch (way) { case "left": path = "Поедешь налево — богатому быть"; break; case "right": path = "Поедешь направо — убитому быть"; break; case "straight": path = "Поедешь прямо — женатому быть"; break; default: path = "Обратно дороги нет"; break; } return path; } public static String heroChoice2(int way){ String result = ""; if (way==1){ result = "Коня потеряешь"; }else if (way==2){ result = "Жизнь потеряешь"; }else if (way==3){ result = "Счастье обретёшь"; }else { result = "Спроси ещё"; } return result; } public static String speedLimit3(int speed) { String result = ""; if (speed <= 50) { result = "Нет нарушений"; } else if (speed <= 65) { result = "устное порицание и лекция на 5 минут"; }else if(speed<=100) { result = "40 Евро штраф"; }else if (speed<=130) { result = "штраф 500 евро"; }else{ result = "штраф в 1000 евро, конфискация прав на 3 года и конфискация транспортного средства"; } return result; } public static String speedLimit2(int speed) { if (speed <= 50) { return "Нет нарушений"; } else if (speed <= 65) { return "устное порицание и лекция на 5 минут"; }else if(speed<=100) { return "40 Евро штраф"; }else if (speed<=130) { return "штраф 500 евро"; }else{ return "штраф в 1000 евро, конфискация прав на 3 года и конфискация транспортного средства"; } } public static void speedLimit(int speed) { if (speed <= 50) { System.out.println("Нет нарушений"); } else if (speed <= 65) { // Java не нравится что здесь написано speed >= 50, но по условию должно быть System.out.println("устное порицание и лекция на 5 минут"); } else if (speed >= 100 && speed <= 130) { System.out.println("штраф 500 евро"); } else if (speed > 130) { System.out.println("штраф в 1000 евро, конфискация прав на 3 года и конфискация транспортного средства"); } } public static void split() { System.out.println("----------------------"); } }
UTF-8
Java
3,859
java
Homework07.java
Java
[]
null
[]
package homeworks; public class Homework07 { public static void main(String[] args) { System.out.println(heroChoice("left")); System.out.println(heroChoice("right")); System.out.println(heroChoice("straight")); split(); int speed = 129; split(); System.out.println(speedLimit2(46)); System.out.println(speedLimit2(56)); System.out.println(speedLimit2(80)); System.out.println(speedLimit2(120)); split(); System.out.println(heroChoice2(1)); System.out.println(heroChoice2(2)); System.out.println(heroChoice2(3)); System.out.println(heroChoice2(4)); split(); } public static String heroChoice(String way) { String path = ""; switch (way) { case "left": path = "Поедешь налево — богатому быть"; break; case "right": path = "Поедешь направо — убитому быть"; break; case "straight": path = "Поедешь прямо — женатому быть"; break; default: path = "Обратно дороги нет"; break; } return path; } public static String heroChoice2(int way){ String result = ""; if (way==1){ result = "Коня потеряешь"; }else if (way==2){ result = "Жизнь потеряешь"; }else if (way==3){ result = "Счастье обретёшь"; }else { result = "Спроси ещё"; } return result; } public static String speedLimit3(int speed) { String result = ""; if (speed <= 50) { result = "Нет нарушений"; } else if (speed <= 65) { result = "устное порицание и лекция на 5 минут"; }else if(speed<=100) { result = "40 Евро штраф"; }else if (speed<=130) { result = "штраф 500 евро"; }else{ result = "штраф в 1000 евро, конфискация прав на 3 года и конфискация транспортного средства"; } return result; } public static String speedLimit2(int speed) { if (speed <= 50) { return "Нет нарушений"; } else if (speed <= 65) { return "устное порицание и лекция на 5 минут"; }else if(speed<=100) { return "40 Евро штраф"; }else if (speed<=130) { return "штраф 500 евро"; }else{ return "штраф в 1000 евро, конфискация прав на 3 года и конфискация транспортного средства"; } } public static void speedLimit(int speed) { if (speed <= 50) { System.out.println("Нет нарушений"); } else if (speed <= 65) { // Java не нравится что здесь написано speed >= 50, но по условию должно быть System.out.println("устное порицание и лекция на 5 минут"); } else if (speed >= 100 && speed <= 130) { System.out.println("штраф 500 евро"); } else if (speed > 130) { System.out.println("штраф в 1000 евро, конфискация прав на 3 года и конфискация транспортного средства"); } } public static void split() { System.out.println("----------------------"); } }
3,859
0.521029
0.491377
108
29.601852
23.651772
117
false
false
0
0
0
0
0
0
0.5
false
false
0
cad144812356f07efa9374865412310b1e8113ee
28,475,633,174,426
0d26d715a0e66246d9a88d1ca77637c208089ec4
/fxadmin/src/main/java/com/ylxx/fx/service/impl/person/systemimpl/OrganizationServiceImpl.java
ae30455e164250581a10b1f34bf3f7171e39b640
[]
no_license
lkp7321/sour
https://github.com/lkp7321/sour
ff997625c920ddbc8f8bd05307184afc748c22b7
06ac40e140bad1dc1e7b3590ce099bc02ae065f2
refs/heads/master
2021-04-12T12:18:22.408000
2018-04-26T06:22:26
2018-04-26T06:22:26
126,673,285
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ylxx.fx.service.impl.person.systemimpl; import java.util.List; import javax.annotation.Resource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import com.alibaba.fastjson.JSON; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.ylxx.fx.core.mapper.person.system.OrganizationMapper; import com.ylxx.fx.service.LogfileCmdService; import com.ylxx.fx.service.person.system.OrganizationService; import com.ylxx.fx.service.po.Logfile; import com.ylxx.fx.service.po.Trd_ogcd; import com.ylxx.fx.utils.CurrUser; import com.ylxx.fx.utils.ErrorCodeSystem; import com.ylxx.fx.utils.LoginUsers; import com.ylxx.fx.utils.ResultDomain; @Service("organService") public class OrganizationServiceImpl implements OrganizationService{ @Resource private OrganizationMapper organmap; @Resource(name="logfileCmdService") private LogfileCmdService logfileCmdService; private static final Logger LOGGER = LoggerFactory.getLogger(OrganizationServiceImpl.class); private List<Trd_ogcd> list = null; //获取当前用户的机构信息 public Trd_ogcd getUserog(String userKey){ CurrUser curUser = LoginUsers.getLoginUser().getCurrUser(userKey); return organmap.queryOgcdLeve(curUser.getOrgn()); } /** * 机构添加 */ public String insert(Trd_ogcd trdOgcd, String userKey){ CurrUser curUser = LoginUsers.getLoginUser().getCurrUser(userKey); try { if(trdOgcd.getLeve().equals("1")){ LOGGER.info("trd_organ 表插入一级分行"); organmap.insertOrgan(trdOgcd); LOGGER.info("trd_ogcd 表插入一级分行"); organmap.insertOgcd(trdOgcd); }else{ organmap.insertOgcd(trdOgcd); } } catch (Exception e) { LOGGER.error(e.getMessage(), e); return ResultDomain.getRtnMsg(ErrorCodeSystem.E_11.getCode(), null); } Logfile logfile = new Logfile(); logfile.setProd(curUser.getProd()); logfile.setUsem(curUser.getUsnm()); logfile.setVnew("成功"); logfile.setVold("登录ip:"+curUser.getCurIP()+"机构号:"+trdOgcd.getOgcd()+"机构名:"+trdOgcd.getOgnm()); logfile.setTymo("机构管理"); logfile.setRemk("机构添加"); logfileCmdService.insertLog(logfile); return ResultDomain.getRtnMsg(ErrorCodeSystem.E_00.getCode(), "机构添加成功"); } //机构修改 public String updateOg(Trd_ogcd trdOgcd, String userKey){ CurrUser curUser = LoginUsers.getLoginUser().getCurrUser(userKey); boolean flag = false; if(trdOgcd.getLeve().equals("1")){ organmap.update(trdOgcd); organmap.updateOgran(trdOgcd); flag = true; }else{ organmap.update(trdOgcd); flag =true; } if(flag){ Logfile logfile = new Logfile(); logfile.setProd(curUser.getProd()); logfile.setUsem(curUser.getUsnm()); logfile.setVnew("成功"); logfile.setVold("登录ip:"+curUser.getCurIP()+"机构号:"+trdOgcd.getOgcd()+"机构名:"+trdOgcd.getOgnm()); logfile.setTymo("机构管理"); logfile.setRemk("机构修改"); logfileCmdService.insertLog(logfile); return ResultDomain.getRtnMsg(ErrorCodeSystem.E_00.getCode(), "机构修改成功"); }else{ return ResultDomain.getRtnMsg(ErrorCodeSystem.E_12.getCode(), null); } } //添加获取数据 public String curLeveList(String userKey, String leve) { CurrUser curUser = LoginUsers.getLoginUser().getCurrUser(userKey); String userogcd = curUser.getCstn(); try{ if (leve.trim().equals("1")) { list = organmap.queryOrgan(); } else if (leve.trim().equals("3")) { list = organmap.oneTwoLeve(); } else { list = organmap.selleve(userogcd); } }catch(Exception e){ LOGGER.error(e.getMessage(),e); } if(list!=null&&list.size()>0){ return ResultDomain.getRtnMsg(ErrorCodeSystem.E_00.getCode(), JSON.toJSONString(list)); }else{ return ResultDomain.getRtnMsg(ErrorCodeSystem.E_13.getCode(), null); } } //修改获取数据 public String organUpList(String userKey, String leve) { CurrUser curUser = LoginUsers.getLoginUser().getCurrUser(userKey); String userogcd = curUser.getCstn(); if (leve.trim().equals("1")) { list = queryOrgans(); } else { list = upQueryOrgan(userogcd); } if(list!=null&&list.size()>0){ return ResultDomain.getRtnMsg(ErrorCodeSystem.E_00.getCode(), list); }else{ return ResultDomain.getRtnMsg(ErrorCodeSystem.E_14.getCode(), null); } } public List<Trd_ogcd> queryOrgans(){ try { list = organmap.queryOrgan(); } catch (Exception e) { LOGGER.error(e.getMessage(),e); } return list; } public List<Trd_ogcd> upQueryOrgan(String userogcd){ try { if(userogcd.equals("0001")){ list = organmap.upQueryOrgan1(); }else{ list = organmap.upQueryOrgan2(userogcd); } } catch (Exception e) { LOGGER.error(e.getMessage(),e); } return list; } //获取合并的下拉框的机构列表 public String getHeBing(String prod, String ogup, String ogcd){ try { list = organmap.queryOneOgcd(prod, ogup, ogcd); } catch (Exception e) { LOGGER.error(e.getMessage(), e); } if(list!=null&&list.size()>0){ return ResultDomain.getRtnMsg(ErrorCodeSystem.E_00.getCode(), JSON.toJSONString(list)); }else{ return ResultDomain.getRtnMsg(ErrorCodeSystem.E_15.getCode(), null); } } //删除机构 public String delog(String userKey,String ogcd){ CurrUser curUser = LoginUsers.getLoginUser().getCurrUser(userKey); int a = 0; int b = 0; a = organmap.queryUser(curUser.getProd(), ogcd); if(a>0){ return ResultDomain.getRtnMsg(ErrorCodeSystem.E_20.getCode(), null);//特殊的弹窗 }else{ b = organmap.deleCytp(ogcd); if(b>0){ Logfile logfile = new Logfile(); logfile.setProd(curUser.getProd()); logfile.setUsem(curUser.getUsnm()); logfile.setVnew("成功"); logfile.setVold("登录ip:"+curUser.getCurIP()+"机构号:"+ogcd); logfile.setTymo("机构管理"); logfile.setRemk("机构删除"); logfileCmdService.insertLog(logfile); return ResultDomain.getRtnMsg(ErrorCodeSystem.E_00.getCode(), "机构删除成功"); }else{ return ResultDomain.getRtnMsg(ErrorCodeSystem.E_19.getCode(), null); } } } //合并机构 public String heBing(String userKey, String newogcd, String oldogcd){ CurrUser curUser = LoginUsers.getLoginUser().getCurrUser(userKey); String prod = curUser.getProd(); int a = 0; try { a = organmap.queryUser(prod, oldogcd); int b = 0; if(a>0){ LOGGER.info("该机构下还有签约用户信息:开始移出"); organmap.updateOgcd(prod,newogcd,oldogcd);//客户ogcd organmap.updateRgog(prod,newogcd,oldogcd);//客户rgog int c = organmap.deleCytp(oldogcd); //删除旧的机构 if(c>0){ return ResultDomain.getRtnMsg(ErrorCodeSystem.E_00.getCode(), "机构合并(删除)成功"); }else{ return ResultDomain.getRtnMsg(ErrorCodeSystem.E_00.getCode(), "机构合并(删除)失败"); } }else{ LOGGER.info("该机构下没有签约用户可以直接删除:"); b = organmap.deleCytp(oldogcd); if(b>0){ return ResultDomain.getRtnMsg(ErrorCodeSystem.E_00.getCode(), "机构合并(删除)成功"); } else{ return ResultDomain.getRtnMsg(ErrorCodeSystem.E_18.getCode(), "机构合并(删除)失败"); } } } catch (Exception e) { LOGGER.error(e.getMessage(), e); return ResultDomain.getRtnMsg(ErrorCodeSystem.E_18.getCode(), "机构合并(删除)失败"); } } //分页获取数据 public PageInfo<Trd_ogcd> getPageAllOgcd(String userKey, Integer pageNo, Integer pageSize) { CurrUser curUser = LoginUsers.getLoginUser().getCurrUser(userKey); Trd_ogcd trdOgcd = organmap.queryOgcdLeve(curUser.getCstn()); pageNo = pageNo == null?1:pageNo; pageSize = pageSize == null?10:pageSize; PageHelper.startPage(pageNo, pageSize); List<Trd_ogcd> lists = null; try { lists = organmap.queryAllOrgan(trdOgcd.getLeve(), trdOgcd.getOgcd()); } catch (Exception e) { LOGGER.error(e.getMessage(), e); } PageInfo<Trd_ogcd> page = new PageInfo<Trd_ogcd>(lists); if(page.getList()!=null&&page.getList().size()>0){ for (int i = 0; i < page.getList().size(); i++) { page.getList().get(i).setUsfg(page.getList().get(i).getUsfg().equals( "0") ? "开启" : "停用"); } } return page; } //获取所有机构列表,未分页 public String getAllOgcd(String userKey){ CurrUser curUser = LoginUsers.getLoginUser().getCurrUser(userKey); Trd_ogcd trdOgcd = organmap.queryOgcdLeve(curUser.getCstn()); list = organmap.queryAllOrgan(trdOgcd.getLeve(), trdOgcd.getOgcd()); if(list!=null&&list.size()>0){ for (int i = 0; i < list.size(); i++) { list.get(i).setUsfg(list.get(i).getUsfg().equals( "0") ? "开启" : "停用"); } return ResultDomain.getRtnMsg(ErrorCodeSystem.E_00.getCode(), list); }else{ return ResultDomain.getRtnMsg(ErrorCodeSystem.E_0.getCode(), null); } } }
UTF-8
Java
8,922
java
OrganizationServiceImpl.java
Java
[]
null
[]
package com.ylxx.fx.service.impl.person.systemimpl; import java.util.List; import javax.annotation.Resource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import com.alibaba.fastjson.JSON; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.ylxx.fx.core.mapper.person.system.OrganizationMapper; import com.ylxx.fx.service.LogfileCmdService; import com.ylxx.fx.service.person.system.OrganizationService; import com.ylxx.fx.service.po.Logfile; import com.ylxx.fx.service.po.Trd_ogcd; import com.ylxx.fx.utils.CurrUser; import com.ylxx.fx.utils.ErrorCodeSystem; import com.ylxx.fx.utils.LoginUsers; import com.ylxx.fx.utils.ResultDomain; @Service("organService") public class OrganizationServiceImpl implements OrganizationService{ @Resource private OrganizationMapper organmap; @Resource(name="logfileCmdService") private LogfileCmdService logfileCmdService; private static final Logger LOGGER = LoggerFactory.getLogger(OrganizationServiceImpl.class); private List<Trd_ogcd> list = null; //获取当前用户的机构信息 public Trd_ogcd getUserog(String userKey){ CurrUser curUser = LoginUsers.getLoginUser().getCurrUser(userKey); return organmap.queryOgcdLeve(curUser.getOrgn()); } /** * 机构添加 */ public String insert(Trd_ogcd trdOgcd, String userKey){ CurrUser curUser = LoginUsers.getLoginUser().getCurrUser(userKey); try { if(trdOgcd.getLeve().equals("1")){ LOGGER.info("trd_organ 表插入一级分行"); organmap.insertOrgan(trdOgcd); LOGGER.info("trd_ogcd 表插入一级分行"); organmap.insertOgcd(trdOgcd); }else{ organmap.insertOgcd(trdOgcd); } } catch (Exception e) { LOGGER.error(e.getMessage(), e); return ResultDomain.getRtnMsg(ErrorCodeSystem.E_11.getCode(), null); } Logfile logfile = new Logfile(); logfile.setProd(curUser.getProd()); logfile.setUsem(curUser.getUsnm()); logfile.setVnew("成功"); logfile.setVold("登录ip:"+curUser.getCurIP()+"机构号:"+trdOgcd.getOgcd()+"机构名:"+trdOgcd.getOgnm()); logfile.setTymo("机构管理"); logfile.setRemk("机构添加"); logfileCmdService.insertLog(logfile); return ResultDomain.getRtnMsg(ErrorCodeSystem.E_00.getCode(), "机构添加成功"); } //机构修改 public String updateOg(Trd_ogcd trdOgcd, String userKey){ CurrUser curUser = LoginUsers.getLoginUser().getCurrUser(userKey); boolean flag = false; if(trdOgcd.getLeve().equals("1")){ organmap.update(trdOgcd); organmap.updateOgran(trdOgcd); flag = true; }else{ organmap.update(trdOgcd); flag =true; } if(flag){ Logfile logfile = new Logfile(); logfile.setProd(curUser.getProd()); logfile.setUsem(curUser.getUsnm()); logfile.setVnew("成功"); logfile.setVold("登录ip:"+curUser.getCurIP()+"机构号:"+trdOgcd.getOgcd()+"机构名:"+trdOgcd.getOgnm()); logfile.setTymo("机构管理"); logfile.setRemk("机构修改"); logfileCmdService.insertLog(logfile); return ResultDomain.getRtnMsg(ErrorCodeSystem.E_00.getCode(), "机构修改成功"); }else{ return ResultDomain.getRtnMsg(ErrorCodeSystem.E_12.getCode(), null); } } //添加获取数据 public String curLeveList(String userKey, String leve) { CurrUser curUser = LoginUsers.getLoginUser().getCurrUser(userKey); String userogcd = curUser.getCstn(); try{ if (leve.trim().equals("1")) { list = organmap.queryOrgan(); } else if (leve.trim().equals("3")) { list = organmap.oneTwoLeve(); } else { list = organmap.selleve(userogcd); } }catch(Exception e){ LOGGER.error(e.getMessage(),e); } if(list!=null&&list.size()>0){ return ResultDomain.getRtnMsg(ErrorCodeSystem.E_00.getCode(), JSON.toJSONString(list)); }else{ return ResultDomain.getRtnMsg(ErrorCodeSystem.E_13.getCode(), null); } } //修改获取数据 public String organUpList(String userKey, String leve) { CurrUser curUser = LoginUsers.getLoginUser().getCurrUser(userKey); String userogcd = curUser.getCstn(); if (leve.trim().equals("1")) { list = queryOrgans(); } else { list = upQueryOrgan(userogcd); } if(list!=null&&list.size()>0){ return ResultDomain.getRtnMsg(ErrorCodeSystem.E_00.getCode(), list); }else{ return ResultDomain.getRtnMsg(ErrorCodeSystem.E_14.getCode(), null); } } public List<Trd_ogcd> queryOrgans(){ try { list = organmap.queryOrgan(); } catch (Exception e) { LOGGER.error(e.getMessage(),e); } return list; } public List<Trd_ogcd> upQueryOrgan(String userogcd){ try { if(userogcd.equals("0001")){ list = organmap.upQueryOrgan1(); }else{ list = organmap.upQueryOrgan2(userogcd); } } catch (Exception e) { LOGGER.error(e.getMessage(),e); } return list; } //获取合并的下拉框的机构列表 public String getHeBing(String prod, String ogup, String ogcd){ try { list = organmap.queryOneOgcd(prod, ogup, ogcd); } catch (Exception e) { LOGGER.error(e.getMessage(), e); } if(list!=null&&list.size()>0){ return ResultDomain.getRtnMsg(ErrorCodeSystem.E_00.getCode(), JSON.toJSONString(list)); }else{ return ResultDomain.getRtnMsg(ErrorCodeSystem.E_15.getCode(), null); } } //删除机构 public String delog(String userKey,String ogcd){ CurrUser curUser = LoginUsers.getLoginUser().getCurrUser(userKey); int a = 0; int b = 0; a = organmap.queryUser(curUser.getProd(), ogcd); if(a>0){ return ResultDomain.getRtnMsg(ErrorCodeSystem.E_20.getCode(), null);//特殊的弹窗 }else{ b = organmap.deleCytp(ogcd); if(b>0){ Logfile logfile = new Logfile(); logfile.setProd(curUser.getProd()); logfile.setUsem(curUser.getUsnm()); logfile.setVnew("成功"); logfile.setVold("登录ip:"+curUser.getCurIP()+"机构号:"+ogcd); logfile.setTymo("机构管理"); logfile.setRemk("机构删除"); logfileCmdService.insertLog(logfile); return ResultDomain.getRtnMsg(ErrorCodeSystem.E_00.getCode(), "机构删除成功"); }else{ return ResultDomain.getRtnMsg(ErrorCodeSystem.E_19.getCode(), null); } } } //合并机构 public String heBing(String userKey, String newogcd, String oldogcd){ CurrUser curUser = LoginUsers.getLoginUser().getCurrUser(userKey); String prod = curUser.getProd(); int a = 0; try { a = organmap.queryUser(prod, oldogcd); int b = 0; if(a>0){ LOGGER.info("该机构下还有签约用户信息:开始移出"); organmap.updateOgcd(prod,newogcd,oldogcd);//客户ogcd organmap.updateRgog(prod,newogcd,oldogcd);//客户rgog int c = organmap.deleCytp(oldogcd); //删除旧的机构 if(c>0){ return ResultDomain.getRtnMsg(ErrorCodeSystem.E_00.getCode(), "机构合并(删除)成功"); }else{ return ResultDomain.getRtnMsg(ErrorCodeSystem.E_00.getCode(), "机构合并(删除)失败"); } }else{ LOGGER.info("该机构下没有签约用户可以直接删除:"); b = organmap.deleCytp(oldogcd); if(b>0){ return ResultDomain.getRtnMsg(ErrorCodeSystem.E_00.getCode(), "机构合并(删除)成功"); } else{ return ResultDomain.getRtnMsg(ErrorCodeSystem.E_18.getCode(), "机构合并(删除)失败"); } } } catch (Exception e) { LOGGER.error(e.getMessage(), e); return ResultDomain.getRtnMsg(ErrorCodeSystem.E_18.getCode(), "机构合并(删除)失败"); } } //分页获取数据 public PageInfo<Trd_ogcd> getPageAllOgcd(String userKey, Integer pageNo, Integer pageSize) { CurrUser curUser = LoginUsers.getLoginUser().getCurrUser(userKey); Trd_ogcd trdOgcd = organmap.queryOgcdLeve(curUser.getCstn()); pageNo = pageNo == null?1:pageNo; pageSize = pageSize == null?10:pageSize; PageHelper.startPage(pageNo, pageSize); List<Trd_ogcd> lists = null; try { lists = organmap.queryAllOrgan(trdOgcd.getLeve(), trdOgcd.getOgcd()); } catch (Exception e) { LOGGER.error(e.getMessage(), e); } PageInfo<Trd_ogcd> page = new PageInfo<Trd_ogcd>(lists); if(page.getList()!=null&&page.getList().size()>0){ for (int i = 0; i < page.getList().size(); i++) { page.getList().get(i).setUsfg(page.getList().get(i).getUsfg().equals( "0") ? "开启" : "停用"); } } return page; } //获取所有机构列表,未分页 public String getAllOgcd(String userKey){ CurrUser curUser = LoginUsers.getLoginUser().getCurrUser(userKey); Trd_ogcd trdOgcd = organmap.queryOgcdLeve(curUser.getCstn()); list = organmap.queryAllOrgan(trdOgcd.getLeve(), trdOgcd.getOgcd()); if(list!=null&&list.size()>0){ for (int i = 0; i < list.size(); i++) { list.get(i).setUsfg(list.get(i).getUsfg().equals( "0") ? "开启" : "停用"); } return ResultDomain.getRtnMsg(ErrorCodeSystem.E_00.getCode(), list); }else{ return ResultDomain.getRtnMsg(ErrorCodeSystem.E_0.getCode(), null); } } }
8,922
0.69812
0.689434
259
31.447876
24.79694
97
false
false
0
0
0
0
0
0
2.903475
false
false
0
cbdcb5eba833b783eea1ac176638da41bfd8ec36
29,411,936,090,438
2b9cc2c6ddd3540b4b2276fccac23c28d37e5c06
/src/main/java/com/microwise/msp/hardware/servlet/StatusServlet.java
4b854a727328756b741d555f114d430c6ae5f537
[]
no_license
algsun/blueplanet-daemon
https://github.com/algsun/blueplanet-daemon
864e5af9477d8e69ffa742deb3bbe141711d30a6
318c790e0eb7753b6ce8b3ba3cd41c539fe7746c
refs/heads/master
2020-03-15T19:47:44.247000
2018-05-31T07:25:02
2018-05-31T07:25:02
132,317,533
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.microwise.msp.hardware.servlet; import com.google.common.base.Strings; import com.jcabi.manifests.Manifests; import org.json.JSONException; import org.json.JSONObject; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; /** * 返回 status * * @author gaohui * @date 13-12-9 14:29 */ public class StatusServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("utf-8"); resp.setCharacterEncoding("utf-8"); resp.setContentType("application/json"); Date startTime = (Date) req.getSession().getServletContext().getAttribute("app.startTime"); JSONObject json = new JSONObject(); try { json.put("name", "blueplanet-daemon"); json.put("uptime", startTime.getTime()); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); json.put("uptime_str", dateFormat.format(startTime)); String svnRevision = readManifest("App-Svn-Revision"); if (!Strings.isNullOrEmpty(svnRevision)) { json.put("svn_revision", Integer.parseInt(svnRevision)); } String appVersion = readManifest("App-Version"); if(!Strings.isNullOrEmpty(appVersion)){ json.put("version", appVersion); } } catch (JSONException e) { e.printStackTrace(); } resp.getWriter().append(json.toString()); resp.getWriter().flush(); } private static String readManifest(String key) { try { return Manifests.read(key); } catch(IllegalArgumentException e) { // do nothing } return null; } }
UTF-8
Java
2,187
java
StatusServlet.java
Java
[ { "context": "rt java.util.Date;\n\n/**\n * 返回 status\n *\n * @author gaohui\n * @date 13-12-9 14:29\n */\npublic class StatusSer", "end": 506, "score": 0.9991520047187805, "start": 500, "tag": "USERNAME", "value": "gaohui" } ]
null
[]
package com.microwise.msp.hardware.servlet; import com.google.common.base.Strings; import com.jcabi.manifests.Manifests; import org.json.JSONException; import org.json.JSONObject; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; /** * 返回 status * * @author gaohui * @date 13-12-9 14:29 */ public class StatusServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("utf-8"); resp.setCharacterEncoding("utf-8"); resp.setContentType("application/json"); Date startTime = (Date) req.getSession().getServletContext().getAttribute("app.startTime"); JSONObject json = new JSONObject(); try { json.put("name", "blueplanet-daemon"); json.put("uptime", startTime.getTime()); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); json.put("uptime_str", dateFormat.format(startTime)); String svnRevision = readManifest("App-Svn-Revision"); if (!Strings.isNullOrEmpty(svnRevision)) { json.put("svn_revision", Integer.parseInt(svnRevision)); } String appVersion = readManifest("App-Version"); if(!Strings.isNullOrEmpty(appVersion)){ json.put("version", appVersion); } } catch (JSONException e) { e.printStackTrace(); } resp.getWriter().append(json.toString()); resp.getWriter().flush(); } private static String readManifest(String key) { try { return Manifests.read(key); } catch(IllegalArgumentException e) { // do nothing } return null; } }
2,187
0.659185
0.654146
66
32.075756
26.885452
114
false
false
0
0
0
0
0
0
0.636364
false
false
0