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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d172085e8843618fb33197e85b7f6456d57db752 | 24,541,443,133,378 | 45cc493651c1270836ef79eec00a36b0610df43b | /src/test/java/com/advanova/maven/extension/dynamic_lifecycle/DynamicLifecycleMavenLifecycleParticipantIT.java | 8d2d78cdb25e042f084f6caf7aef6ab4c1efd638 | [] | no_license | advanova/dynamic-lifecycle-maven-extension | https://github.com/advanova/dynamic-lifecycle-maven-extension | aea4532f76634e9c3762cba2b3937e362a47ed88 | 97d0c5604c1fb2952ed46e1a49200c94221186b0 | refs/heads/main | 2023-08-10T16:11:51.631000 | 2021-09-14T09:06:24 | 2021-09-14T09:12:56 | 406,292,411 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.advanova.maven.extension.dynamic_lifecycle;
import com.soebes.itf.jupiter.extension.MavenGoal;
import com.soebes.itf.jupiter.extension.MavenJupiterExtension;
import com.soebes.itf.jupiter.extension.MavenTest;
import com.soebes.itf.jupiter.maven.MavenExecutionResult;
import org.assertj.core.api.Assertions;
import static com.soebes.itf.extension.assertj.MavenITAssertions.assertThat;
@MavenJupiterExtension
class DynamicLifecycleMavenLifecycleParticipantIT {
@MavenTest
@MavenGoal("my_test")
void testLifecycle(MavenExecutionResult result) {
assertThat(result).isSuccessful();
assertThat(result.getMavenLog()).info().contains("--- echo-maven-plugin:0.4.0:echo (echo-info) @ dynamic-lifecycle-maven-extension-test ---");
}
} | UTF-8 | Java | 772 | java | DynamicLifecycleMavenLifecycleParticipantIT.java | Java | [] | null | [] | package com.advanova.maven.extension.dynamic_lifecycle;
import com.soebes.itf.jupiter.extension.MavenGoal;
import com.soebes.itf.jupiter.extension.MavenJupiterExtension;
import com.soebes.itf.jupiter.extension.MavenTest;
import com.soebes.itf.jupiter.maven.MavenExecutionResult;
import org.assertj.core.api.Assertions;
import static com.soebes.itf.extension.assertj.MavenITAssertions.assertThat;
@MavenJupiterExtension
class DynamicLifecycleMavenLifecycleParticipantIT {
@MavenTest
@MavenGoal("my_test")
void testLifecycle(MavenExecutionResult result) {
assertThat(result).isSuccessful();
assertThat(result.getMavenLog()).info().contains("--- echo-maven-plugin:0.4.0:echo (echo-info) @ dynamic-lifecycle-maven-extension-test ---");
}
} | 772 | 0.784974 | 0.781088 | 21 | 35.809525 | 35.517426 | 150 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false | 9 |
cd5e286583278add9d855c983bdff04bf147954a | 4,466,765,992,506 | f83c869a7cea4f5d9be1f5caeef02806d349b0b0 | /src/main/java/mateusz/webapp/userprofile/UserProfileService.java | c80b09f1eb5cf0b65cac68c57dbb0b4ceb599887 | [] | no_license | MateuszP21/CarShop | https://github.com/MateuszP21/CarShop | b763bb80c3d96472589497dc7d800ef839aaface | dfbd82768c5de1434e3e80117fb69c95292fa907 | refs/heads/master | 2018-11-20T23:45:01.080000 | 2018-09-20T17:43:18 | 2018-09-20T17:43:18 | 121,747,057 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package mateusz.webapp.userprofile;
import mateusz.webapp.AuthenticationFacade;
import mateusz.webapp.dao.UserRepository;
import mateusz.webapp.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
@Service
class UserProfileService {
private UserRepository userRepository;
private AuthenticationFacade authenticationFacade;
@Autowired
public UserProfileService(UserRepository userRepository,
AuthenticationFacade authenticationFacade) {
this.userRepository = userRepository;
this.authenticationFacade = authenticationFacade;
}
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
public void changeUsername(User user, String username) {
user.setUsername(username);
userRepository.save(user);
}
public void changeEmail(User user, String email) {
user.setEmail(email);
userRepository.save(user);
}
public boolean passwordMatchesOldNew(String password, User user) {
return passwordEncoder().matches(password,user.getPassword());
}
public void changePassword(String newPassword, User user) {
user.setPassword(passwordEncoder().encode(newPassword));
userRepository.save(user);
}
public boolean passwordMatchesConfirmAndNew(ChangePasswordModel changePasswordModel) {
return changePasswordModel.getNewPassword().equals(changePasswordModel.getConfirmNewPassword());
}
public boolean passwordMatchesOld(String oldPassword, User user) {
return passwordEncoder().matches(oldPassword,user.getPassword());
}
public boolean emailExists(String email) {
return userRepository.findByEmail(email) != null;
}
public boolean usernameExists(String username) {
return userRepository.findByUsername(username) != null;
}
public User findCurrentUser() {
return userRepository.findByUsername(authenticationFacade.getCurrentUsernameLogged());
}
}
| UTF-8 | Java | 2,159 | java | UserProfileService.java | Java | [] | null | [] | package mateusz.webapp.userprofile;
import mateusz.webapp.AuthenticationFacade;
import mateusz.webapp.dao.UserRepository;
import mateusz.webapp.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
@Service
class UserProfileService {
private UserRepository userRepository;
private AuthenticationFacade authenticationFacade;
@Autowired
public UserProfileService(UserRepository userRepository,
AuthenticationFacade authenticationFacade) {
this.userRepository = userRepository;
this.authenticationFacade = authenticationFacade;
}
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
public void changeUsername(User user, String username) {
user.setUsername(username);
userRepository.save(user);
}
public void changeEmail(User user, String email) {
user.setEmail(email);
userRepository.save(user);
}
public boolean passwordMatchesOldNew(String password, User user) {
return passwordEncoder().matches(password,user.getPassword());
}
public void changePassword(String newPassword, User user) {
user.setPassword(passwordEncoder().encode(newPassword));
userRepository.save(user);
}
public boolean passwordMatchesConfirmAndNew(ChangePasswordModel changePasswordModel) {
return changePasswordModel.getNewPassword().equals(changePasswordModel.getConfirmNewPassword());
}
public boolean passwordMatchesOld(String oldPassword, User user) {
return passwordEncoder().matches(oldPassword,user.getPassword());
}
public boolean emailExists(String email) {
return userRepository.findByEmail(email) != null;
}
public boolean usernameExists(String username) {
return userRepository.findByUsername(username) != null;
}
public User findCurrentUser() {
return userRepository.findByUsername(authenticationFacade.getCurrentUsernameLogged());
}
}
| 2,159 | 0.736915 | 0.736915 | 64 | 32.734375 | 29.162928 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 9 |
3bfe4e4fccfd27dfc6ab300e0c402dccb875272d | 32,134,945,366,559 | 1947aaf5c9b972122e1e640610eafb0631a6954f | /src/main/cdn/message/MessageRegisterNode.java | 1c355750effa2f111cc59624eacb4962953a38c6 | [] | no_license | anoopyadav/DMDS | https://github.com/anoopyadav/DMDS | 337f53ed7e76b5100cd90933a1bec466866fbc13 | a333fa44ec689f9c2641e395fc77043c3694e180 | refs/heads/master | 2016-04-01T10:37:56.228000 | 2015-04-25T21:10:48 | 2015-04-25T21:10:48 | 31,490,002 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package main.cdn.message;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import main.cdn.message.MessageType;
/*
+-------------------------------+
|*****MessageRegisterRequest****|
+-------------------------------+
| MessageType(int) | |
+-------------------------------+
| MessageLength(int) |
+-------------------------------+
| IpAddress(String) |
+-------------------------------+
| TcpPortNumber(int) |
+-------------------------------+
| UdpPortNumber(int) |
+-------------------------------+
| AssignedId(String) |
+-------------------------------+
*/
public class MessageRegisterNode implements Message {
private int m_messageType;
private int m_messageLength;
private String m_ipAddress;
private int m_tcpPortNumber;
private int m_udpPortNumber;
private String m_assignedID;
private byte[] m_message;
public MessageRegisterNode(String ipAddress, int tcpPortNumber, int udpPortNumber, String assignedID) {
m_messageType = MessageType.REGISTER_NODE.GetIntegerMessageType();
m_ipAddress = ipAddress;
m_tcpPortNumber = tcpPortNumber;
m_udpPortNumber = udpPortNumber;
m_assignedID = assignedID;
m_messageLength = 4 * INTEGER_LENGTH + m_ipAddress.length() + m_assignedID.length();
}
public MessageRegisterNode(byte[] messageData) {
m_message = messageData;
}
public void Pack() throws IOException {
ByteArrayOutputStream baOutputStream = new ByteArrayOutputStream();
DataOutputStream dOut = new DataOutputStream(new BufferedOutputStream(baOutputStream));
dOut.writeInt(m_messageType);
dOut.writeInt(m_messageLength);
dOut.writeUTF(m_ipAddress);
dOut.writeInt(m_tcpPortNumber);
dOut.writeInt(m_udpPortNumber);
dOut.writeUTF(m_assignedID);
dOut.flush();
m_message = baOutputStream.toByteArray();
baOutputStream.close();
dOut.close();
}
public void Unpack() throws IOException {
ByteArrayInputStream baInputStream = new ByteArrayInputStream(m_message);
DataInputStream dIn = new DataInputStream(new BufferedInputStream(baInputStream));
m_messageType = dIn.readInt();
m_messageLength = dIn.readInt();
m_ipAddress = dIn.readUTF();
m_tcpPortNumber = dIn.readInt();
m_udpPortNumber = dIn.readInt();
m_assignedID = dIn.readUTF();
baInputStream.close();
dIn.close();
}
public MessageType GetMessageType() {
return MessageType.ValueOf(m_messageType);
}
public int GetMessageLength() {
return m_messageLength;
}
public String GetIpAddress() {
return m_ipAddress;
}
public int GetTcpPort() {
return m_tcpPortNumber;
}
public int GetUdpPort() {
return m_udpPortNumber;
}
public String GetAssignedID() {
return m_assignedID;
}
public byte[] GetRawMessage() {
return m_message;
}
}
| UTF-8 | Java | 2,980 | java | MessageRegisterNode.java | Java | [] | null | [] | package main.cdn.message;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import main.cdn.message.MessageType;
/*
+-------------------------------+
|*****MessageRegisterRequest****|
+-------------------------------+
| MessageType(int) | |
+-------------------------------+
| MessageLength(int) |
+-------------------------------+
| IpAddress(String) |
+-------------------------------+
| TcpPortNumber(int) |
+-------------------------------+
| UdpPortNumber(int) |
+-------------------------------+
| AssignedId(String) |
+-------------------------------+
*/
public class MessageRegisterNode implements Message {
private int m_messageType;
private int m_messageLength;
private String m_ipAddress;
private int m_tcpPortNumber;
private int m_udpPortNumber;
private String m_assignedID;
private byte[] m_message;
public MessageRegisterNode(String ipAddress, int tcpPortNumber, int udpPortNumber, String assignedID) {
m_messageType = MessageType.REGISTER_NODE.GetIntegerMessageType();
m_ipAddress = ipAddress;
m_tcpPortNumber = tcpPortNumber;
m_udpPortNumber = udpPortNumber;
m_assignedID = assignedID;
m_messageLength = 4 * INTEGER_LENGTH + m_ipAddress.length() + m_assignedID.length();
}
public MessageRegisterNode(byte[] messageData) {
m_message = messageData;
}
public void Pack() throws IOException {
ByteArrayOutputStream baOutputStream = new ByteArrayOutputStream();
DataOutputStream dOut = new DataOutputStream(new BufferedOutputStream(baOutputStream));
dOut.writeInt(m_messageType);
dOut.writeInt(m_messageLength);
dOut.writeUTF(m_ipAddress);
dOut.writeInt(m_tcpPortNumber);
dOut.writeInt(m_udpPortNumber);
dOut.writeUTF(m_assignedID);
dOut.flush();
m_message = baOutputStream.toByteArray();
baOutputStream.close();
dOut.close();
}
public void Unpack() throws IOException {
ByteArrayInputStream baInputStream = new ByteArrayInputStream(m_message);
DataInputStream dIn = new DataInputStream(new BufferedInputStream(baInputStream));
m_messageType = dIn.readInt();
m_messageLength = dIn.readInt();
m_ipAddress = dIn.readUTF();
m_tcpPortNumber = dIn.readInt();
m_udpPortNumber = dIn.readInt();
m_assignedID = dIn.readUTF();
baInputStream.close();
dIn.close();
}
public MessageType GetMessageType() {
return MessageType.ValueOf(m_messageType);
}
public int GetMessageLength() {
return m_messageLength;
}
public String GetIpAddress() {
return m_ipAddress;
}
public int GetTcpPort() {
return m_tcpPortNumber;
}
public int GetUdpPort() {
return m_udpPortNumber;
}
public String GetAssignedID() {
return m_assignedID;
}
public byte[] GetRawMessage() {
return m_message;
}
}
| 2,980 | 0.657383 | 0.657047 | 111 | 25.846848 | 20.730879 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.81982 | false | false | 9 |
4e0bcfde83826b6707e1c11b4f248f942b25f49f | 21,345,987,524,285 | 424b0b4c68eed5d578a0d952e7c2af5672da8d9b | /src/main/java/com/springangular/repositories/EnvironmentsRepository.java | 35d570031dc45ed391fde8a0e149f0e4cdc00e3c | [] | no_license | MicaeFortis/MichalWochnikPortfolioSpring | https://github.com/MicaeFortis/MichalWochnikPortfolioSpring | c58fa80f82f53cc09985accfa1c570d970a89209 | 52288c97a63ad431a3aae6831e11b65ada01981a | refs/heads/master | 2017-12-05T09:34:14.511000 | 2017-04-05T21:12:11 | 2017-04-05T21:12:11 | 86,498,268 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.springangular.repositories;
import com.springangular.models.Environments;
import org.springframework.data.repository.CrudRepository;
import java.util.List;
/**
* Created by MichalPC on 2017-02-22.
*/
public interface EnvironmentsRepository extends CrudRepository<Environments, Long> {
List<Environments> findAll();
}
| UTF-8 | Java | 338 | java | EnvironmentsRepository.java | Java | [
{
"context": "sitory;\n\nimport java.util.List;\n\n/**\n * Created by MichalPC on 2017-02-22.\n */\npublic interface EnvironmentsR",
"end": 197,
"score": 0.9985027313232422,
"start": 189,
"tag": "USERNAME",
"value": "MichalPC"
}
] | null | [] | package com.springangular.repositories;
import com.springangular.models.Environments;
import org.springframework.data.repository.CrudRepository;
import java.util.List;
/**
* Created by MichalPC on 2017-02-22.
*/
public interface EnvironmentsRepository extends CrudRepository<Environments, Long> {
List<Environments> findAll();
}
| 338 | 0.795858 | 0.772189 | 13 | 25 | 26.020702 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.461538 | false | false | 9 |
07e0ace3ce549635901f71822b2017725976964d | 7,945,689,497,745 | 9facf8dbfb479807502bd0e6192df47d443c0c64 | /app/src/main/java/com/android/ww/wwframe/mode/base/DialogHelper.java | 63893666ccbedd291aca8884e972ba7266f7c091 | [] | no_license | sourfeng/MMFrame | https://github.com/sourfeng/MMFrame | d93a60ebcd5d76788af6a206f3ea95604c4a1b52 | 7e1167df35d24d2e1acf9c2209082c6e2ed74589 | refs/heads/master | 2021-01-11T17:59:33.773000 | 2017-02-07T02:02:17 | 2017-02-07T02:02:17 | 79,892,250 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.android.ww.wwframe.mode.base;
import android.app.ProgressDialog;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import com.android.ww.wwframe.R;
import ww.com.core.ScreenUtil;
/**
* Created by feng on 2017/1/24.
* 请求弹框
*/
public class DialogHelper {
private ProgressDialog dialog;
private Context context;
private boolean isShow; //dialog (true:显示;false:不显示)
public DialogHelper(Context context, boolean isShow) {
this.context = context;
this.isShow = isShow;
initDialog();
}
private void initDialog() {
if (dialog == null) {
View view = LayoutInflater.from(context).inflate(R.layout.view_loading, null);
ScreenUtil.scale(view);
dialog = new ProgressDialog(context, R.style.LoadingDialog);
dialog.setCanceledOnTouchOutside(false); //点击不消失,返回消失
// dialog.setCancelable(false); //点击或返回都不消失
show();
dialog.setContentView(view);
}
}
public void dismiss() {
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
}
public void show() {
if (dialog != null && !dialog.isShowing()) {
dialog.show();
}
}
}
| UTF-8 | Java | 1,368 | java | DialogHelper.java | Java | [
{
"context": "\nimport ww.com.core.ScreenUtil;\n\n/**\n * Created by feng on 2017/1/24.\n * 请求弹框\n */\n\npublic class DialogHel",
"end": 261,
"score": 0.9994733929634094,
"start": 257,
"tag": "USERNAME",
"value": "feng"
}
] | null | [] | package com.android.ww.wwframe.mode.base;
import android.app.ProgressDialog;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import com.android.ww.wwframe.R;
import ww.com.core.ScreenUtil;
/**
* Created by feng on 2017/1/24.
* 请求弹框
*/
public class DialogHelper {
private ProgressDialog dialog;
private Context context;
private boolean isShow; //dialog (true:显示;false:不显示)
public DialogHelper(Context context, boolean isShow) {
this.context = context;
this.isShow = isShow;
initDialog();
}
private void initDialog() {
if (dialog == null) {
View view = LayoutInflater.from(context).inflate(R.layout.view_loading, null);
ScreenUtil.scale(view);
dialog = new ProgressDialog(context, R.style.LoadingDialog);
dialog.setCanceledOnTouchOutside(false); //点击不消失,返回消失
// dialog.setCancelable(false); //点击或返回都不消失
show();
dialog.setContentView(view);
}
}
public void dismiss() {
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
}
public void show() {
if (dialog != null && !dialog.isShowing()) {
dialog.show();
}
}
}
| 1,368 | 0.61026 | 0.6049 | 57 | 21.912281 | 21.598637 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.438596 | false | false | 9 |
8da28777c19c0afda8e94a4b5591488ce8f56cfc | 21,019,569,953,345 | 5a1759b0dbe9c153a70e4724468fba3ddd5f3e7f | /src/main/java/co/monos/blog/domain/Post.java | 034ac5b159204f5716ed4351e559af25311da8eb | [] | no_license | jeseon/blog | https://github.com/jeseon/blog | 09d02ce2501ddc4dbbe42cb30ef395310f0f67ac | 79a7eab1c1489a0ab600c7981d4a236ee6672ce3 | refs/heads/master | 2021-01-11T07:00:19.069000 | 2017-01-10T00:42:49 | 2017-01-10T00:42:49 | 71,968,370 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package co.monos.blog.domain;
import java.util.Calendar;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Null;
import javax.validation.constraints.Size;
import lombok.Data;
@Data
@Entity
public class Post {
@Id
@GeneratedValue
private int id;
@NotNull
@Size(min = 1, max = 255)
private String title;
@Null
private String subtitle;
@NotNull
@Size(min = 1, max = 4000)
private String content;
@NotNull
private Date createdAt = Calendar.getInstance().getTime();
@ManyToOne
private Member member;
} | UTF-8 | Java | 713 | java | Post.java | Java | [] | null | [] | package co.monos.blog.domain;
import java.util.Calendar;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Null;
import javax.validation.constraints.Size;
import lombok.Data;
@Data
@Entity
public class Post {
@Id
@GeneratedValue
private int id;
@NotNull
@Size(min = 1, max = 255)
private String title;
@Null
private String subtitle;
@NotNull
@Size(min = 1, max = 4000)
private String content;
@NotNull
private Date createdAt = Calendar.getInstance().getTime();
@ManyToOne
private Member member;
} | 713 | 0.771388 | 0.758766 | 39 | 17.307692 | 15.253674 | 59 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.871795 | false | false | 9 |
9442cd2d714c8abc2ab5ae951a8e18bb2e44cec3 | 36,043,365,576,374 | 566cff07bc79628c18253dc61d46f8451c2d6ff2 | /src/game/battleship/players/Player.java | 5adfdccfab1d904ff8d7697c53a160cfabb4ae92 | [] | no_license | jaygohel83/BattleShipGame | https://github.com/jaygohel83/BattleShipGame | 878ab9d850a0231b546c7480299a712e048e0c6a | b8d0222dd084e49c32375af342271282253f47d8 | refs/heads/master | 2021-01-23T23:46:07.482000 | 2018-02-24T11:53:26 | 2018-02-24T11:53:26 | 122,735,092 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package game.battleship.players;
import game.battleship.utility.BattleShipConstant;
import java.util.Arrays;
/**
* @author Jay Gohel
* player of the game
*/
public class Player {
private String playerName;
private BattleshipArea area;
private String[] missileSequence;
private int hitCounter = 0;
private boolean playing = false;
public Player(String pName, String battleArea)
{
playerName = pName;
area = new BattleshipArea(battleArea);
}
/**
* @param type
* @param dimW
* @param dimH
* @param origin
*/
public void placeBattleShip(String type, int dimW, int dimH, String origin)
{
area.placeBattleShip(type, dimW, dimH, origin);
}
/**
* @return missleSquenceArraylist
*/
public String[] getMissileSequence() {
return missileSequence;
}
public void setMissileSequence(String[] missileSequence) {
this.missileSequence = missileSequence;
}
public String getPlayerName() {
return playerName;
}
public BattleshipArea getBattleArea() {
return area;
}
public int getHitCounter() {
return hitCounter;
}
/**
* updating hit counter once player shoot missile
*/
public void updateHitCounter()
{
if(hasMoreMissiles())
{
hitCounter = hitCounter+1;
System.out.println(playerName + " hitcounter update " + hitCounter);
}
else
{
System.out.println(playerName + " hit counter not updated");
}
}
/**
* @return flag if player has missile to shot or not
*/
public boolean hasMoreMissiles()
{
return(hitCounter < missileSequence.length);
}
/**
* @return target
*/
public String getNextTarget()
{
String target = BattleShipConstant.FINISHED;
if(hasMoreMissiles())
{
target = missileSequence[hitCounter];
updateHitCounter();
}
return target;
}
/**
* @return flag if player is playing or not
*/
public boolean isPlaying() {
return playing;
}
public void setPlaying(boolean playing) {
this.playing = playing;
}
@Override
public String toString() {
return "Player [area=" + area + ", hitCounter=" + hitCounter
+ ", missileSequence=" + Arrays.toString(missileSequence)
+ ", playerName=" + playerName + "]";
}
}
| UTF-8 | Java | 2,167 | java | Player.java | Java | [
{
"context": "nstant;\n\nimport java.util.Arrays;\n\n\n/**\n * @author Jay Gohel\n * player of the game\n */\npublic class Player {\n\t",
"end": 137,
"score": 0.9998739361763,
"start": 128,
"tag": "NAME",
"value": "Jay Gohel"
}
] | null | [] | package game.battleship.players;
import game.battleship.utility.BattleShipConstant;
import java.util.Arrays;
/**
* @author <NAME>
* player of the game
*/
public class Player {
private String playerName;
private BattleshipArea area;
private String[] missileSequence;
private int hitCounter = 0;
private boolean playing = false;
public Player(String pName, String battleArea)
{
playerName = pName;
area = new BattleshipArea(battleArea);
}
/**
* @param type
* @param dimW
* @param dimH
* @param origin
*/
public void placeBattleShip(String type, int dimW, int dimH, String origin)
{
area.placeBattleShip(type, dimW, dimH, origin);
}
/**
* @return missleSquenceArraylist
*/
public String[] getMissileSequence() {
return missileSequence;
}
public void setMissileSequence(String[] missileSequence) {
this.missileSequence = missileSequence;
}
public String getPlayerName() {
return playerName;
}
public BattleshipArea getBattleArea() {
return area;
}
public int getHitCounter() {
return hitCounter;
}
/**
* updating hit counter once player shoot missile
*/
public void updateHitCounter()
{
if(hasMoreMissiles())
{
hitCounter = hitCounter+1;
System.out.println(playerName + " hitcounter update " + hitCounter);
}
else
{
System.out.println(playerName + " hit counter not updated");
}
}
/**
* @return flag if player has missile to shot or not
*/
public boolean hasMoreMissiles()
{
return(hitCounter < missileSequence.length);
}
/**
* @return target
*/
public String getNextTarget()
{
String target = BattleShipConstant.FINISHED;
if(hasMoreMissiles())
{
target = missileSequence[hitCounter];
updateHitCounter();
}
return target;
}
/**
* @return flag if player is playing or not
*/
public boolean isPlaying() {
return playing;
}
public void setPlaying(boolean playing) {
this.playing = playing;
}
@Override
public String toString() {
return "Player [area=" + area + ", hitCounter=" + hitCounter
+ ", missileSequence=" + Arrays.toString(missileSequence)
+ ", playerName=" + playerName + "]";
}
}
| 2,164 | 0.68251 | 0.681587 | 118 | 17.364407 | 19.094175 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.508475 | false | false | 9 |
f5bad15fe12f40a396e8f05f8e1f4f0e350fb971 | 38,903,813,776,357 | 7ebddd1b09bc622fcd8a5481a5dbb036f8d8172a | /src/wrapperclasses/StrinEvenOddposition.java | b4017ab43348a59c75fbe49aef61e71a03d3aa59 | [] | no_license | smrcc/DemoRepo | https://github.com/smrcc/DemoRepo | 541696b508b050d9a6a6716bf9c836252f35d49d | 63d5f601f779181588033cc7f3bedb178a9ff8ea | refs/heads/master | 2020-05-30T14:55:18.524000 | 2019-06-02T06:49:40 | 2019-06-02T06:49:40 | 189,804,293 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package wrapperclasses;
public class StrinEvenOddposition {
public static void main(String[] args)
{
String str="ABCDEFGHIJ";
String s1="";
String s2="";
for(int i=0;i<str.length();i++)
{
if(i%2==0)
{
s1=s1+str.charAt(i);
}if(i%2==1)
{
s2=s2+str.charAt(i);
}
}
System.out.println("odd positions:"+ s1);
System.out.println("Even positions:"+ s2);
}
}
| UTF-8 | Java | 394 | java | StrinEvenOddposition.java | Java | [] | null | [] | package wrapperclasses;
public class StrinEvenOddposition {
public static void main(String[] args)
{
String str="ABCDEFGHIJ";
String s1="";
String s2="";
for(int i=0;i<str.length();i++)
{
if(i%2==0)
{
s1=s1+str.charAt(i);
}if(i%2==1)
{
s2=s2+str.charAt(i);
}
}
System.out.println("odd positions:"+ s1);
System.out.println("Even positions:"+ s2);
}
}
| 394 | 0.596447 | 0.563452 | 25 | 14.76 | 14.367408 | 42 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.96 | false | false | 9 |
08c8bb7e26b2808bbad9d3f78b9588ad1e63231a | 37,512,244,375,162 | 124df74bce796598d224c4380c60c8e95756f761 | /com.raytheon.viz.ui/src/com/raytheon/viz/ui/dialogs/SWTMessageBox.java | 0f45b95b1325ccf96eaf726e10961789f508e9e0 | [] | no_license | Mapoet/AWIPS-Test | https://github.com/Mapoet/AWIPS-Test | 19059bbd401573950995c8cc442ddd45588e6c9f | 43c5a7cc360b3cbec2ae94cb58594fe247253621 | refs/heads/master | 2020-04-17T03:35:57.762000 | 2017-02-06T17:17:58 | 2017-02-06T17:17:58 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.viz.ui.dialogs;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Layout;
import org.eclipse.swt.widgets.Shell;
/**
* This is a message box that will only block the parent shell and not the
* entire application.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Apr 7, 2011 lvenable Initial creation
* Oct 18, 2012 1229 rferrel Made dialog non-blocking.
*
* </pre>
*
* @author lvenable
* @version 1.0
*/
public class SWTMessageBox extends CaveSWTDialogBase {
/**
* Label displaying the icon.
*/
private Label iconLbl;
/**
* Label displaying the message.
*/
private Label messageLbl;
/**
* The SWT icon to be displayed.
*/
private int swtIcon = 0;
/**
* The SWT styles to determine the icon and buttons to use.
*/
private int swtMessageBoxStyle = 0;
/**
* Number of buttons to be displayed.
*/
private int btnCount = 0;
/**
* Message to be displayed.
*/
private String message = "";
private boolean centerMessage = false;
/**
* Constructor.
*
* @param parent
* Parent shell.
* @param title
* Dialog title.
* @param message
* Message.
* @param swtMessageBoxStyle
* Style for icon and buttons.
*/
public SWTMessageBox(Shell parent, String title, String message,
int swtMessageBoxStyle) {
this(parent, title, message, swtMessageBoxStyle, SWT.PRIMARY_MODAL,
false);
}
public SWTMessageBox(Shell parent, String title, String message,
int swtMessageBoxStyle, int modalSetting, boolean centerMessage) {
super(parent, SWT.DIALOG_TRIM | modalSetting, CAVE.DO_NOT_BLOCK);
this.swtMessageBoxStyle = swtMessageBoxStyle;
this.message = message;
this.centerMessage = centerMessage;
setText(title);
}
@Override
protected Layout constructShellLayout() {
// Create the main layout for the shell.
GridLayout mainLayout = new GridLayout(1, false);
mainLayout.verticalSpacing = 15;
return mainLayout;
}
@Override
protected Object constructShellLayoutData() {
return new GridData(SWT.FILL, SWT.DEFAULT, true, false);
}
/*
* (non-Javadoc)
*
* @see
* swtconfirmationdialog.CaveSWTDialogBase#initializeComponents(org.eclipse
* .swt.widgets.Shell)
*/
@Override
protected void initializeComponents(Shell shell) {
determineLabelIcon();
createIconAndLabel();
createBottomButtons();
}
/**
* Create the icon label (in needed) and the message label.
*/
private void createIconAndLabel() {
int numberOfGridCells = 1;
int labelStyle = SWT.NONE;
if (swtIcon != 0) {
numberOfGridCells = 2;
}
if (centerMessage) {
labelStyle = SWT.CENTER;
}
Composite iconLabelComp = new Composite(shell, SWT.NONE);
GridLayout gl = new GridLayout(numberOfGridCells, false);
gl.horizontalSpacing = 20;
iconLabelComp.setLayout(gl);
if (swtIcon != 0) {
iconLbl = new Label(iconLabelComp, SWT.NONE);
iconLbl.setImage(getDisplay().getSystemImage(swtIcon));
}
GridData gd = new GridData(SWT.FILL, SWT.CENTER, false, true);
gd.widthHint = 300;
messageLbl = new Label(iconLabelComp, SWT.WRAP | labelStyle);
messageLbl.setText(message);
messageLbl.setLayoutData(gd);
}
/**
* Create the bottom buttons.
*/
private void createBottomButtons() {
int buttonWidth = 80;
GridData gd = new GridData(SWT.CENTER, SWT.DEFAULT, true, false);
Composite mainButtonComp = new Composite(shell, SWT.NONE);
mainButtonComp.setLayout(new GridLayout(getButtonCount(), false));
mainButtonComp.setLayoutData(gd);
if (hasStyleAttributes(SWT.OK)) {
gd = new GridData(buttonWidth, SWT.DEFAULT);
Button okBtn = new Button(mainButtonComp, SWT.PUSH);
okBtn.setText("OK");
okBtn.setLayoutData(gd);
okBtn.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
setReturnValue(new Integer(SWT.OK));
close();
}
});
if (hasStyleAttributes(SWT.CANCEL)) {
setReturnValue(new Integer(SWT.CANCEL));
gd = new GridData(buttonWidth, SWT.DEFAULT);
Button cancelBtn = new Button(mainButtonComp, SWT.PUSH);
cancelBtn.setText("Cancel");
cancelBtn.setLayoutData(gd);
cancelBtn.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
setReturnValue(new Integer(SWT.CANCEL));
close();
}
});
}
} else if (hasStyleAttributes(SWT.YES | SWT.NO)) {
setReturnValue(new Integer(SWT.NO));
gd = new GridData(buttonWidth, SWT.DEFAULT);
Button yesBtn = new Button(mainButtonComp, SWT.PUSH);
yesBtn.setText("Yes");
yesBtn.setLayoutData(gd);
yesBtn.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
setReturnValue(new Integer(SWT.YES));
close();
}
});
gd = new GridData(buttonWidth, SWT.DEFAULT);
Button noBtn = new Button(mainButtonComp, SWT.PUSH);
noBtn.setText("No");
noBtn.setLayoutData(gd);
noBtn.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
setReturnValue(new Integer(SWT.NO));
close();
}
});
}
}
/**
* Determine the icon to be displayed in the icon label.
*/
private void determineLabelIcon() {
/*
* Find the SWT icon to use
*/
if (hasStyleAttributes(SWT.ICON_ERROR)) {
swtIcon = SWT.ICON_ERROR;
} else if (hasStyleAttributes(SWT.ICON_INFORMATION)) {
swtIcon = SWT.ICON_INFORMATION;
} else if (hasStyleAttributes(SWT.ICON_QUESTION)) {
swtIcon = SWT.ICON_QUESTION;
} else if (hasStyleAttributes(SWT.ICON_WARNING)) {
swtIcon = SWT.ICON_WARNING;
}
}
/**
* Get the number of buttons to be displayed.
*
* @return
*/
private int getButtonCount() {
btnCount = 2;
if (hasStyleAttributes(SWT.OK | SWT.CANCEL)) {
btnCount = 2;
} else if (hasStyleAttributes(SWT.YES | SWT.NO)) {
btnCount = 2;
} else {
btnCount = 1;
}
return btnCount;
}
/**
* Determine if the style contains a certain attribute.
*
* @param attribute
* Attribute.
* @return True if the style contains an attribute.
*/
private boolean hasStyleAttributes(int attribute) {
return (swtMessageBoxStyle & attribute) == attribute;
}
}
| UTF-8 | Java | 8,735 | java | SWTMessageBox.java | Java | [
{
"context": "------------------------\n * Apr 7, 2011 lvenable Initial creation\n * Oct 18, 2012 1229 r",
"end": 1507,
"score": 0.9996926188468933,
"start": 1499,
"tag": "USERNAME",
"value": "lvenable"
},
{
"context": "le Initial creation\n * Oct 18, 2012 1229 rferrel Made dialog non-blocking.\n * \n * </pre>\n * \n ",
"end": 1563,
"score": 0.9996638894081116,
"start": 1556,
"tag": "USERNAME",
"value": "rferrel"
},
{
"context": " dialog non-blocking.\n * \n * </pre>\n * \n * @author lvenable\n * @version 1.0\n */\npublic class SWTMessageBox ex",
"end": 1631,
"score": 0.9995915293693542,
"start": 1623,
"tag": "USERNAME",
"value": "lvenable"
}
] | null | [] | /**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.viz.ui.dialogs;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Layout;
import org.eclipse.swt.widgets.Shell;
/**
* This is a message box that will only block the parent shell and not the
* entire application.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Apr 7, 2011 lvenable Initial creation
* Oct 18, 2012 1229 rferrel Made dialog non-blocking.
*
* </pre>
*
* @author lvenable
* @version 1.0
*/
public class SWTMessageBox extends CaveSWTDialogBase {
/**
* Label displaying the icon.
*/
private Label iconLbl;
/**
* Label displaying the message.
*/
private Label messageLbl;
/**
* The SWT icon to be displayed.
*/
private int swtIcon = 0;
/**
* The SWT styles to determine the icon and buttons to use.
*/
private int swtMessageBoxStyle = 0;
/**
* Number of buttons to be displayed.
*/
private int btnCount = 0;
/**
* Message to be displayed.
*/
private String message = "";
private boolean centerMessage = false;
/**
* Constructor.
*
* @param parent
* Parent shell.
* @param title
* Dialog title.
* @param message
* Message.
* @param swtMessageBoxStyle
* Style for icon and buttons.
*/
public SWTMessageBox(Shell parent, String title, String message,
int swtMessageBoxStyle) {
this(parent, title, message, swtMessageBoxStyle, SWT.PRIMARY_MODAL,
false);
}
public SWTMessageBox(Shell parent, String title, String message,
int swtMessageBoxStyle, int modalSetting, boolean centerMessage) {
super(parent, SWT.DIALOG_TRIM | modalSetting, CAVE.DO_NOT_BLOCK);
this.swtMessageBoxStyle = swtMessageBoxStyle;
this.message = message;
this.centerMessage = centerMessage;
setText(title);
}
@Override
protected Layout constructShellLayout() {
// Create the main layout for the shell.
GridLayout mainLayout = new GridLayout(1, false);
mainLayout.verticalSpacing = 15;
return mainLayout;
}
@Override
protected Object constructShellLayoutData() {
return new GridData(SWT.FILL, SWT.DEFAULT, true, false);
}
/*
* (non-Javadoc)
*
* @see
* swtconfirmationdialog.CaveSWTDialogBase#initializeComponents(org.eclipse
* .swt.widgets.Shell)
*/
@Override
protected void initializeComponents(Shell shell) {
determineLabelIcon();
createIconAndLabel();
createBottomButtons();
}
/**
* Create the icon label (in needed) and the message label.
*/
private void createIconAndLabel() {
int numberOfGridCells = 1;
int labelStyle = SWT.NONE;
if (swtIcon != 0) {
numberOfGridCells = 2;
}
if (centerMessage) {
labelStyle = SWT.CENTER;
}
Composite iconLabelComp = new Composite(shell, SWT.NONE);
GridLayout gl = new GridLayout(numberOfGridCells, false);
gl.horizontalSpacing = 20;
iconLabelComp.setLayout(gl);
if (swtIcon != 0) {
iconLbl = new Label(iconLabelComp, SWT.NONE);
iconLbl.setImage(getDisplay().getSystemImage(swtIcon));
}
GridData gd = new GridData(SWT.FILL, SWT.CENTER, false, true);
gd.widthHint = 300;
messageLbl = new Label(iconLabelComp, SWT.WRAP | labelStyle);
messageLbl.setText(message);
messageLbl.setLayoutData(gd);
}
/**
* Create the bottom buttons.
*/
private void createBottomButtons() {
int buttonWidth = 80;
GridData gd = new GridData(SWT.CENTER, SWT.DEFAULT, true, false);
Composite mainButtonComp = new Composite(shell, SWT.NONE);
mainButtonComp.setLayout(new GridLayout(getButtonCount(), false));
mainButtonComp.setLayoutData(gd);
if (hasStyleAttributes(SWT.OK)) {
gd = new GridData(buttonWidth, SWT.DEFAULT);
Button okBtn = new Button(mainButtonComp, SWT.PUSH);
okBtn.setText("OK");
okBtn.setLayoutData(gd);
okBtn.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
setReturnValue(new Integer(SWT.OK));
close();
}
});
if (hasStyleAttributes(SWT.CANCEL)) {
setReturnValue(new Integer(SWT.CANCEL));
gd = new GridData(buttonWidth, SWT.DEFAULT);
Button cancelBtn = new Button(mainButtonComp, SWT.PUSH);
cancelBtn.setText("Cancel");
cancelBtn.setLayoutData(gd);
cancelBtn.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
setReturnValue(new Integer(SWT.CANCEL));
close();
}
});
}
} else if (hasStyleAttributes(SWT.YES | SWT.NO)) {
setReturnValue(new Integer(SWT.NO));
gd = new GridData(buttonWidth, SWT.DEFAULT);
Button yesBtn = new Button(mainButtonComp, SWT.PUSH);
yesBtn.setText("Yes");
yesBtn.setLayoutData(gd);
yesBtn.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
setReturnValue(new Integer(SWT.YES));
close();
}
});
gd = new GridData(buttonWidth, SWT.DEFAULT);
Button noBtn = new Button(mainButtonComp, SWT.PUSH);
noBtn.setText("No");
noBtn.setLayoutData(gd);
noBtn.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
setReturnValue(new Integer(SWT.NO));
close();
}
});
}
}
/**
* Determine the icon to be displayed in the icon label.
*/
private void determineLabelIcon() {
/*
* Find the SWT icon to use
*/
if (hasStyleAttributes(SWT.ICON_ERROR)) {
swtIcon = SWT.ICON_ERROR;
} else if (hasStyleAttributes(SWT.ICON_INFORMATION)) {
swtIcon = SWT.ICON_INFORMATION;
} else if (hasStyleAttributes(SWT.ICON_QUESTION)) {
swtIcon = SWT.ICON_QUESTION;
} else if (hasStyleAttributes(SWT.ICON_WARNING)) {
swtIcon = SWT.ICON_WARNING;
}
}
/**
* Get the number of buttons to be displayed.
*
* @return
*/
private int getButtonCount() {
btnCount = 2;
if (hasStyleAttributes(SWT.OK | SWT.CANCEL)) {
btnCount = 2;
} else if (hasStyleAttributes(SWT.YES | SWT.NO)) {
btnCount = 2;
} else {
btnCount = 1;
}
return btnCount;
}
/**
* Determine if the style contains a certain attribute.
*
* @param attribute
* Attribute.
* @return True if the style contains an attribute.
*/
private boolean hasStyleAttributes(int attribute) {
return (swtMessageBoxStyle & attribute) == attribute;
}
}
| 8,735 | 0.578821 | 0.570807 | 274 | 30.879562 | 22.628952 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.510949 | false | false | 9 |
61c317c38350f9964dbbed1a13bae57bf242ed9a | 9,526,237,504,272 | b64703c519a96750efea8fcdaf35946f07f5aaf8 | /miniProject2/plugins/de.luh.se.mbse.network.textualeditor/src-gen/de/luh/se/mbse/network/textualeditor/amf/Channel.java | cbb6bef8ca61bda7536e97f5b607eecb304c8f0f | [] | no_license | iFadi/MDSE | https://github.com/iFadi/MDSE | 48048b25184aef0005b46c595d9331d34e70d8c5 | fee0d715db68645ff85e9168d4c0fbcc08ef9352 | refs/heads/master | 2021-01-20T20:48:57.815000 | 2016-07-11T13:39:58 | 2016-07-11T13:39:58 | 60,011,652 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* generated by Xtext 2.9.1
*/
package de.luh.se.mbse.network.textualeditor.amf;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EObject;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Channel</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* </p>
* <ul>
* <li>{@link de.luh.se.mbse.network.textualeditor.amf.Channel#getType <em>Type</em>}</li>
* <li>{@link de.luh.se.mbse.network.textualeditor.amf.Channel#getName <em>Name</em>}</li>
* </ul>
*
* @see de.luh.se.mbse.network.textualeditor.amf.AmfPackage#getChannel()
* @model
* @generated
*/
public interface Channel extends EObject
{
/**
* Returns the value of the '<em><b>Type</b></em>' attribute list.
* The list contents are of type {@link de.luh.se.mbse.network.textualeditor.amf.TypeOfChannel}.
* The literals are from the enumeration {@link de.luh.se.mbse.network.textualeditor.amf.TypeOfChannel}.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Type</em>' attribute list isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Type</em>' attribute list.
* @see de.luh.se.mbse.network.textualeditor.amf.TypeOfChannel
* @see de.luh.se.mbse.network.textualeditor.amf.AmfPackage#getChannel_Type()
* @model unique="false"
* @generated
*/
EList<TypeOfChannel> getType();
/**
* Returns the value of the '<em><b>Name</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Name</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Name</em>' attribute.
* @see #setName(String)
* @see de.luh.se.mbse.network.textualeditor.amf.AmfPackage#getChannel_Name()
* @model
* @generated
*/
String getName();
/**
* Sets the value of the '{@link de.luh.se.mbse.network.textualeditor.amf.Channel#getName <em>Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Name</em>' attribute.
* @see #getName()
* @generated
*/
void setName(String value);
} // Channel
| UTF-8 | Java | 2,299 | java | Channel.java | Java | [] | null | [] | /**
* generated by Xtext 2.9.1
*/
package de.luh.se.mbse.network.textualeditor.amf;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EObject;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Channel</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* </p>
* <ul>
* <li>{@link de.luh.se.mbse.network.textualeditor.amf.Channel#getType <em>Type</em>}</li>
* <li>{@link de.luh.se.mbse.network.textualeditor.amf.Channel#getName <em>Name</em>}</li>
* </ul>
*
* @see de.luh.se.mbse.network.textualeditor.amf.AmfPackage#getChannel()
* @model
* @generated
*/
public interface Channel extends EObject
{
/**
* Returns the value of the '<em><b>Type</b></em>' attribute list.
* The list contents are of type {@link de.luh.se.mbse.network.textualeditor.amf.TypeOfChannel}.
* The literals are from the enumeration {@link de.luh.se.mbse.network.textualeditor.amf.TypeOfChannel}.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Type</em>' attribute list isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Type</em>' attribute list.
* @see de.luh.se.mbse.network.textualeditor.amf.TypeOfChannel
* @see de.luh.se.mbse.network.textualeditor.amf.AmfPackage#getChannel_Type()
* @model unique="false"
* @generated
*/
EList<TypeOfChannel> getType();
/**
* Returns the value of the '<em><b>Name</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Name</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Name</em>' attribute.
* @see #setName(String)
* @see de.luh.se.mbse.network.textualeditor.amf.AmfPackage#getChannel_Name()
* @model
* @generated
*/
String getName();
/**
* Sets the value of the '{@link de.luh.se.mbse.network.textualeditor.amf.Channel#getName <em>Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Name</em>' attribute.
* @see #getName()
* @generated
*/
void setName(String value);
} // Channel
| 2,299 | 0.636799 | 0.635494 | 73 | 30.493151 | 30.104441 | 118 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.109589 | false | false | 9 |
ff2473469f5ba1b67235e9fec68dd56115f916f7 | 35,235,911,739,412 | 850296a56b8c0c11b78b045309fefb27604d467d | /app/src/main/java/com/example/jzg/myapplication/utils/MD5Utils.java | 7a548accae249476a818ef9432522c9b132ec1ae | [] | no_license | libodeveloper/BaseProject | https://github.com/libodeveloper/BaseProject | 8cadd2cf4d936582e1964a4bbb980c3c555baa4e | ae90744226aa3c2164b946a31f633e34c496a201 | refs/heads/master | 2021-07-07T00:52:43.619000 | 2021-05-26T02:48:10 | 2021-05-26T02:48:10 | 89,577,274 | 4 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* Project Name:JZGPingGuShi
* File Name:MD5Utils.java
* Package Name:com.gc.jzgpinggushi.uitls
* Date:2014-9-1上午10:38:59
* Copyright (c) 2014, wangyd523@gmail.com All Rights Reserved.
*
*/
package com.example.jzg.myapplication.utils;
import android.text.TextUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* ClassName:MD5Utils <br/>
* Function: TODO ADD FUNCTION. <br/>
* Reason: TODO ADD REASON. <br/>
* Date: 2014-9-1 上午10:38:59 <br/>
*
* @author 汪渝栋
* @version
* @since JDK 1.6
* @see
*/
public class MD5Utils {
private static String TAG = "MD5Utils";
public static Map<String,String> encryptParams(Map<String,String> params){
Map<String,Object> map = new HashMap<>();
map.putAll(params);
String sign = getMD5Sign(map);
params.put("sign",sign);
LogUtil.e(TAG,UIUtils.getUrl(params));
return params;
}
/**
* MD5加密 MD5Encrypt: <br/>
*
* @author wang
* @param inStr
* @return
* @since JDK 1.6
*/
public static String MD5Encrypt(String inStr)
{
MessageDigest md = null;
String outStr = null;
try
{
md = MessageDigest.getInstance("MD5"); // 可以选中其他的算法如SHA
byte[] digest = md.digest(inStr.getBytes());
// 返回的是byet[],要转化为String存储比较方便
outStr = bytetoString(digest);
} catch (NoSuchAlgorithmException nsae)
{
nsae.printStackTrace();
}
return outStr;
}
public static String bytetoString(byte[] digest)
{
String str = "";
String tempStr = "";
for (int i = 1; i < digest.length; i++)
{
tempStr = (Integer.toHexString(digest[i] & 0xff));
if (tempStr.length() == 1)
{
str = str + "0" + tempStr;
} else
{
str = str + tempStr;
}
}
return str.toLowerCase();
}
/*private static final String PRIVATE_KEY = "2CB3147B-D93C-964B-47AE-EEE448C84E3C"
.toLowerCase();*/
private static final String PRIVATE_KEY = "2CB3147B-D93C-964B-47AE-EEE448C84E3C"
.toLowerCase();
/**
*
* getMD5Sign
*
* @Title: getMD5Sign
* @Description: 获取MD5加密后的sign字符串
* @param @param params 需要传递的参数Map集合,无参状态下可以为null
* @return String
* @throws
*/
public static String getMD5Sign(Map<String, Object> params)
{
//params.put("tokenid","6");//根据项目加密
if (params == null || params.size() <= 0)
return newMD5(PRIVATE_KEY);
StringBuffer signValue = new StringBuffer();
List<Map.Entry<String, Object>> infos = sortTreeMap(params);
for (int i = 0; i < infos.size(); i++)
{
if(!TextUtils.isEmpty(infos.get(i).toString())){
String value = infos.get(i).toString();
signValue.append(value);
}
}
signValue.append(PRIVATE_KEY);
// System.out.println("signValue.toString().toLowerCase() is "
// + signValue.toString().toLowerCase());
return newMD5(signValue.toString().toLowerCase());
}
/**
*
* getMD5Sign
*
* @Title: getMD5Sign
* @Description: 获取MD5加密后的sign字符串
* @param @param params 需要传递的参数Map集合,无参状态下可以为null
* @return String
* @throws
*/
public static String getMD5Sign(Map<String, Object> params, String Key)
{
// Key = Key.toLowerCase();
//params.put("tokenid","6");//根据项目加密
if (params == null || params.size() <= 0)
return newMD5(Key.toLowerCase());
StringBuffer signValue = new StringBuffer();
List<Map.Entry<String, Object>> infos = sortTreeMap(params);
for (int i = 0; i < infos.size(); i++)
{
if(!TextUtils.isEmpty(infos.get(i).toString())){
String value = infos.get(i).toString();
signValue.append(value);
}
}
signValue.append(Key.toLowerCase());
// System.out.println("signValue.toString().toLowerCase() is "
// + signValue.toString().toLowerCase());
return newMD5(signValue.toString().toLowerCase());
}
/**
*
* sortTreeMap
*
* @Title: sortTreeMap
* @Description: 对参数列表进行排序(按照key的字母大小)
* @param @param params
* @param @return
* @return Map<String,Object>
* @throws
*/
private static List<Map.Entry<String, Object>> sortTreeMap(
Map<String, Object> params)
{
List<Map.Entry<String, Object>> entrys = new ArrayList<Map.Entry<String, Object>>(
params.entrySet());
// 排序
Collections.sort(entrys, new Comparator<Map.Entry<String, Object>>()
{
public int compare(Map.Entry<String, Object> o1,
Map.Entry<String, Object> o2)
{
return (o1.getKey()).toLowerCase().compareTo(
o2.getKey().toLowerCase());
}
});
return entrys;
}
/**
*
* MD5
*
* @Title: MD5
* @Description: MD5加密方法
* @param @param s 需要加密的字符串
* @param @return
* @return String
* @throws
*/
private final static String newMD5(String s)
{
char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f' };
try
{
byte[] strTemp = s.getBytes("UTF-8");
MessageDigest mdTemp = MessageDigest.getInstance("MD5");
mdTemp.update(strTemp);
byte[] md = mdTemp.digest();
int j = md.length;
char str[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++)
{
byte byte0 = md[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str).toUpperCase();
} catch (Exception e)
{
return null;
}
}
public static String encode(String password){
try {
MessageDigest digest = MessageDigest.getInstance("MD5");
byte[] result = digest.digest(password.getBytes());
StringBuilder sb = new StringBuilder();
for (byte b : result) {
int number = b & 0xff; //加盐 | 0x23
String str = Integer.toHexString(number);
if(str.length()==1){
sb.append("0");
}
sb.append(str);
}
return sb.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return "";
}
}
/**
* 获取文件的MD5值
*
* @param file 文件路径
* @return md5
*/
public static String getFileMd5(String fileName) {
File file = new File(fileName);
MessageDigest messageDigest;
//MappedByteBuffer byteBuffer = null;
FileInputStream fis = null;
try {
messageDigest = MessageDigest.getInstance("MD5");
if (file == null) {
return "";
}
if (!file.exists()) {
return "";
}
int len = 0;
fis = new FileInputStream(file);
//普通流读取方式
byte[] buffer = new byte[1024 * 1024 * 10];
while ((len = fis.read(buffer)) > 0) {
//该对象通过使用 update()方法处理数据
messageDigest.update(buffer, 0, len);
}
BigInteger bigInt = new BigInteger(1, messageDigest.digest());
String md5 = bigInt.toString(16);
while (md5.length() < 32) {
md5 = "0" + md5;
}
return md5;
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
fis = null;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return "";
}
}
| UTF-8 | Java | 7,609 | java | MD5Utils.java | Java | [
{
"context": "\n * Date:2014-9-1上午10:38:59\n * Copyright (c) 2014, wangyd523@gmail.com All Rights Reserved.\n *\n */\n\npackage com.example.",
"end": 171,
"score": 0.9999175071716309,
"start": 152,
"tag": "EMAIL",
"value": "wangyd523@gmail.com"
},
{
"context": "\n * Date: 2014-9-1 上午10:38:59 <br/>\n * \n * @author 汪渝栋\n * @version\n * @since JDK 1.6\n * @see\n */\npublic ",
"end": 826,
"score": 0.9997066259384155,
"start": 823,
"tag": "NAME",
"value": "汪渝栋"
},
{
"context": "\n\t/**\n\t * MD5加密 MD5Encrypt: <br/>\n\t * \n\t * @author wang\n\t * @param inStr\n\t * @return\n\t * @since JDK 1.6\n\t",
"end": 1254,
"score": 0.8259129524230957,
"start": 1250,
"tag": "USERNAME",
"value": "wang"
},
{
"context": "\t}\n\n\t/*private static final String PRIVATE_KEY = \"2CB3147B-D93C-964B-47AE-EEE448C84E3C\"\n\t\t\t.toLowerCase();*/\n\tprivate static final Strin",
"end": 2120,
"score": 0.9997572898864746,
"start": 2084,
"tag": "KEY",
"value": "2CB3147B-D93C-964B-47AE-EEE448C84E3C"
},
{
"context": "();*/\n\tprivate static final String PRIVATE_KEY = \"2CB3147B-D93C-964B-47AE-EEE448C84E3C\"\n\t\t\t.toLowerCase();\n\n\t/**\n\t * \n\t * getMD5Sign\n\t *",
"end": 2223,
"score": 0.9997578263282776,
"start": 2187,
"tag": "KEY",
"value": "2CB3147B-D93C-964B-47AE-EEE448C84E3C"
}
] | null | [] | /**
* Project Name:JZGPingGuShi
* File Name:MD5Utils.java
* Package Name:com.gc.jzgpinggushi.uitls
* Date:2014-9-1上午10:38:59
* Copyright (c) 2014, <EMAIL> All Rights Reserved.
*
*/
package com.example.jzg.myapplication.utils;
import android.text.TextUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* ClassName:MD5Utils <br/>
* Function: TODO ADD FUNCTION. <br/>
* Reason: TODO ADD REASON. <br/>
* Date: 2014-9-1 上午10:38:59 <br/>
*
* @author 汪渝栋
* @version
* @since JDK 1.6
* @see
*/
public class MD5Utils {
private static String TAG = "MD5Utils";
public static Map<String,String> encryptParams(Map<String,String> params){
Map<String,Object> map = new HashMap<>();
map.putAll(params);
String sign = getMD5Sign(map);
params.put("sign",sign);
LogUtil.e(TAG,UIUtils.getUrl(params));
return params;
}
/**
* MD5加密 MD5Encrypt: <br/>
*
* @author wang
* @param inStr
* @return
* @since JDK 1.6
*/
public static String MD5Encrypt(String inStr)
{
MessageDigest md = null;
String outStr = null;
try
{
md = MessageDigest.getInstance("MD5"); // 可以选中其他的算法如SHA
byte[] digest = md.digest(inStr.getBytes());
// 返回的是byet[],要转化为String存储比较方便
outStr = bytetoString(digest);
} catch (NoSuchAlgorithmException nsae)
{
nsae.printStackTrace();
}
return outStr;
}
public static String bytetoString(byte[] digest)
{
String str = "";
String tempStr = "";
for (int i = 1; i < digest.length; i++)
{
tempStr = (Integer.toHexString(digest[i] & 0xff));
if (tempStr.length() == 1)
{
str = str + "0" + tempStr;
} else
{
str = str + tempStr;
}
}
return str.toLowerCase();
}
/*private static final String PRIVATE_KEY = "<KEY>"
.toLowerCase();*/
private static final String PRIVATE_KEY = "<KEY>"
.toLowerCase();
/**
*
* getMD5Sign
*
* @Title: getMD5Sign
* @Description: 获取MD5加密后的sign字符串
* @param @param params 需要传递的参数Map集合,无参状态下可以为null
* @return String
* @throws
*/
public static String getMD5Sign(Map<String, Object> params)
{
//params.put("tokenid","6");//根据项目加密
if (params == null || params.size() <= 0)
return newMD5(PRIVATE_KEY);
StringBuffer signValue = new StringBuffer();
List<Map.Entry<String, Object>> infos = sortTreeMap(params);
for (int i = 0; i < infos.size(); i++)
{
if(!TextUtils.isEmpty(infos.get(i).toString())){
String value = infos.get(i).toString();
signValue.append(value);
}
}
signValue.append(PRIVATE_KEY);
// System.out.println("signValue.toString().toLowerCase() is "
// + signValue.toString().toLowerCase());
return newMD5(signValue.toString().toLowerCase());
}
/**
*
* getMD5Sign
*
* @Title: getMD5Sign
* @Description: 获取MD5加密后的sign字符串
* @param @param params 需要传递的参数Map集合,无参状态下可以为null
* @return String
* @throws
*/
public static String getMD5Sign(Map<String, Object> params, String Key)
{
// Key = Key.toLowerCase();
//params.put("tokenid","6");//根据项目加密
if (params == null || params.size() <= 0)
return newMD5(Key.toLowerCase());
StringBuffer signValue = new StringBuffer();
List<Map.Entry<String, Object>> infos = sortTreeMap(params);
for (int i = 0; i < infos.size(); i++)
{
if(!TextUtils.isEmpty(infos.get(i).toString())){
String value = infos.get(i).toString();
signValue.append(value);
}
}
signValue.append(Key.toLowerCase());
// System.out.println("signValue.toString().toLowerCase() is "
// + signValue.toString().toLowerCase());
return newMD5(signValue.toString().toLowerCase());
}
/**
*
* sortTreeMap
*
* @Title: sortTreeMap
* @Description: 对参数列表进行排序(按照key的字母大小)
* @param @param params
* @param @return
* @return Map<String,Object>
* @throws
*/
private static List<Map.Entry<String, Object>> sortTreeMap(
Map<String, Object> params)
{
List<Map.Entry<String, Object>> entrys = new ArrayList<Map.Entry<String, Object>>(
params.entrySet());
// 排序
Collections.sort(entrys, new Comparator<Map.Entry<String, Object>>()
{
public int compare(Map.Entry<String, Object> o1,
Map.Entry<String, Object> o2)
{
return (o1.getKey()).toLowerCase().compareTo(
o2.getKey().toLowerCase());
}
});
return entrys;
}
/**
*
* MD5
*
* @Title: MD5
* @Description: MD5加密方法
* @param @param s 需要加密的字符串
* @param @return
* @return String
* @throws
*/
private final static String newMD5(String s)
{
char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f' };
try
{
byte[] strTemp = s.getBytes("UTF-8");
MessageDigest mdTemp = MessageDigest.getInstance("MD5");
mdTemp.update(strTemp);
byte[] md = mdTemp.digest();
int j = md.length;
char str[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++)
{
byte byte0 = md[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str).toUpperCase();
} catch (Exception e)
{
return null;
}
}
public static String encode(String password){
try {
MessageDigest digest = MessageDigest.getInstance("MD5");
byte[] result = digest.digest(password.getBytes());
StringBuilder sb = new StringBuilder();
for (byte b : result) {
int number = b & 0xff; //加盐 | 0x23
String str = Integer.toHexString(number);
if(str.length()==1){
sb.append("0");
}
sb.append(str);
}
return sb.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return "";
}
}
/**
* 获取文件的MD5值
*
* @param file 文件路径
* @return md5
*/
public static String getFileMd5(String fileName) {
File file = new File(fileName);
MessageDigest messageDigest;
//MappedByteBuffer byteBuffer = null;
FileInputStream fis = null;
try {
messageDigest = MessageDigest.getInstance("MD5");
if (file == null) {
return "";
}
if (!file.exists()) {
return "";
}
int len = 0;
fis = new FileInputStream(file);
//普通流读取方式
byte[] buffer = new byte[1024 * 1024 * 10];
while ((len = fis.read(buffer)) > 0) {
//该对象通过使用 update()方法处理数据
messageDigest.update(buffer, 0, len);
}
BigInteger bigInt = new BigInteger(1, messageDigest.digest());
String md5 = bigInt.toString(16);
while (md5.length() < 32) {
md5 = "0" + md5;
}
return md5;
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
fis = null;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return "";
}
}
| 7,535 | 0.636389 | 0.613577 | 314 | 22.175159 | 19.155363 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.273885 | false | false | 9 |
f056e14f9fea52efe0f5b3a12729d75340bded9f | 33,775,622,868,547 | a17ffd912c04f92f9a92b90bf25b89fd7dddacf3 | /src/main/java/ua/pb/task/manager/config/AppConfig.java | 1ed910b23f2b36ce112ddcbb90be3e2c06a9c7fd | [] | no_license | r0ndom/taskManagerV2 | https://github.com/r0ndom/taskManagerV2 | b8cc537e04e013b965571f3218e6c54c71edbf9f | be1436391af00b2210fedd987750faf4b29a331f | refs/heads/master | 2021-01-21T13:30:12.026000 | 2016-04-20T08:05:39 | 2016-04-20T08:05:39 | 54,705,429 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ua.pb.task.manager.config;
import org.springframework.context.annotation.*;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
/**
* Created by Mednikov on 26.02.2016.
*/
@Configuration
@ComponentScan(basePackages = {"ua.pb.task.manager.repository", "ua.pb.task.manager.form",
"ua.pb.task.manager.service", "ua.pb.task.manager.util"})
@Import({ActivitiConfig.class, DataSourceConfig.class, GoogleConfig.class, EmailConfig.class})
public class AppConfig {
@Bean
public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
return new PropertySourcesPlaceholderConfigurer();
}
}
| UTF-8 | Java | 661 | java | AppConfig.java | Java | [
{
"context": "rtySourcesPlaceholderConfigurer;\n\n/**\n* Created by Mednikov on 26.02.2016.\n*/\n@Configuration\n@ComponentScan(b",
"end": 192,
"score": 0.9448928236961365,
"start": 184,
"tag": "USERNAME",
"value": "Mednikov"
}
] | null | [] | package ua.pb.task.manager.config;
import org.springframework.context.annotation.*;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
/**
* Created by Mednikov on 26.02.2016.
*/
@Configuration
@ComponentScan(basePackages = {"ua.pb.task.manager.repository", "ua.pb.task.manager.form",
"ua.pb.task.manager.service", "ua.pb.task.manager.util"})
@Import({ActivitiConfig.class, DataSourceConfig.class, GoogleConfig.class, EmailConfig.class})
public class AppConfig {
@Bean
public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
return new PropertySourcesPlaceholderConfigurer();
}
}
| 661 | 0.768533 | 0.75643 | 20 | 32.049999 | 33.251278 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 9 |
09c54a9c84c7ae1c31dcedf7d14f94fd3d45b755 | 38,182,259,276,926 | 680c7582d4df6e7dc17ff59c5718ff883e12a085 | /retrokit/src/main/java/com/theah64/retrokit/utils/StringUtils.java | 4a91e4541eaaace62483eb2aa00a40fe8fb3fbfe | [
"Apache-2.0"
] | permissive | theapache64/RetroKit | https://github.com/theapache64/RetroKit | 2180707d6a466a0ffae153c3fbb044947e72e4a5 | 40b9f560273d9a97c54dc0e17b359bc17f10f450 | refs/heads/master | 2021-01-19T22:59:18.497000 | 2018-09-22T07:42:37 | 2018-09-22T07:42:37 | 101,259,851 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.theah64.retrokit.utils;
import java.text.NumberFormat;
import java.util.Random;
/**
* Created by theapache64 on 16/11/17.
*/
public class StringUtils {
private static final String randomEngine = "0123456789AaBbCcDdEeFfGgHhIiJjKkLkMmNnOoPpQqRrSsTtUuVvWwXxYyZz";
private static Random random;
public static String getRandomString(final int length) {
if (random == null) {
random = new Random();
}
final StringBuilder apiKeyBuilder = new StringBuilder();
for (int i = 0; i < length; i++) {
apiKeyBuilder.append(randomEngine.charAt(random.nextInt(randomEngine.length())));
}
return apiKeyBuilder.toString();
}
public static String getRandomFilename(final int fileNameLength, final String fileExtension) {
return getRandomString(fileNameLength) + fileExtension;
}
public static String getProper(int count, final String singular) {
return getProper(count, singular, singular + "s");
}
private static String getProper(int count, String singular, String plural) {
return count > 1 ? plural : singular;
}
public static String getProperWithCount(int count, String singular) {
return count + " " + getProper(count, singular);
}
public static String toIndianNumber(long totalHits) {
StringBuilder number = new StringBuilder(String.valueOf(totalHits));
if (totalHits != -1) {
final int totalLength = number.length();
if (totalLength >= 4) {
//Format it
switch (totalLength) {
case 4:
return number.insert(1, ",").toString();
case 5:
return number.insert(2, ",").toString();
case 6:
return number.insert(1, ",").insert(4, ",").toString();
case 7:
return number.insert(2, ",").insert(6, ",").toString();
case 8:
return number.insert(1, ",").insert(4, ",").insert(7, ",").toString();
case 9:
return number.insert(2, ",").insert(5, ",").insert(8, ",").toString();
default:
return NumberFormat.getInstance().format(totalHits);
}
}
}
return number.toString();
}
public static String toIndianNumber(String count) {
return toIndianNumber(Long.parseLong(count));
}
}
| UTF-8 | Java | 2,587 | java | StringUtils.java | Java | [
{
"context": "package com.theah64.retrokit.utils;\n\nimport java.text.NumberFormat;\ni",
"end": 19,
"score": 0.6276554465293884,
"start": 17,
"tag": "USERNAME",
"value": "64"
},
{
"context": "ormat;\nimport java.util.Random;\n\n/**\n * Created by theapache64 on 16/11/17.\n */\n\npublic class StringUtils {\n\n ",
"end": 123,
"score": 0.9995112419128418,
"start": 112,
"tag": "USERNAME",
"value": "theapache64"
},
{
"context": "\n private static final String randomEngine = \"0123456789AaBbCcDdEeFfGgHhIiJjKkLkMmNnOoPpQqRrSsTtUuVvWwXxYyZz\";\n private static Random random;\n\n\n public ",
"end": 280,
"score": 0.8606831431388855,
"start": 219,
"tag": "KEY",
"value": "123456789AaBbCcDdEeFfGgHhIiJjKkLkMmNnOoPpQqRrSsTtUuVvWwXxYyZz"
}
] | null | [] | package com.theah64.retrokit.utils;
import java.text.NumberFormat;
import java.util.Random;
/**
* Created by theapache64 on 16/11/17.
*/
public class StringUtils {
private static final String randomEngine = "0<KEY>";
private static Random random;
public static String getRandomString(final int length) {
if (random == null) {
random = new Random();
}
final StringBuilder apiKeyBuilder = new StringBuilder();
for (int i = 0; i < length; i++) {
apiKeyBuilder.append(randomEngine.charAt(random.nextInt(randomEngine.length())));
}
return apiKeyBuilder.toString();
}
public static String getRandomFilename(final int fileNameLength, final String fileExtension) {
return getRandomString(fileNameLength) + fileExtension;
}
public static String getProper(int count, final String singular) {
return getProper(count, singular, singular + "s");
}
private static String getProper(int count, String singular, String plural) {
return count > 1 ? plural : singular;
}
public static String getProperWithCount(int count, String singular) {
return count + " " + getProper(count, singular);
}
public static String toIndianNumber(long totalHits) {
StringBuilder number = new StringBuilder(String.valueOf(totalHits));
if (totalHits != -1) {
final int totalLength = number.length();
if (totalLength >= 4) {
//Format it
switch (totalLength) {
case 4:
return number.insert(1, ",").toString();
case 5:
return number.insert(2, ",").toString();
case 6:
return number.insert(1, ",").insert(4, ",").toString();
case 7:
return number.insert(2, ",").insert(6, ",").toString();
case 8:
return number.insert(1, ",").insert(4, ",").insert(7, ",").toString();
case 9:
return number.insert(2, ",").insert(5, ",").insert(8, ",").toString();
default:
return NumberFormat.getInstance().format(totalHits);
}
}
}
return number.toString();
}
public static String toIndianNumber(String count) {
return toIndianNumber(Long.parseLong(count));
}
}
| 2,531 | 0.560495 | 0.54426 | 88 | 28.386364 | 30.358252 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.659091 | false | false | 9 |
8cbe43eb6621ab0f44488d1d4cb96c4fce636767 | 32,504,312,512,945 | e1aed023a7772ef2e04678f1feb4ac72e2b74d66 | /src/leetcode/string/_680_ValidPalindromeII.java | 6bd0bf7b2db21d96e33ef8b38834a0d1a58077fe | [] | no_license | linweifreedom/LeetCode | https://github.com/linweifreedom/LeetCode | dcf830526a12e05c3d5dff0902206b200f41f2b1 | 6b6123e0c83e2377548450fb9eb0438a40552a76 | refs/heads/master | 2022-09-01T21:10:31.171000 | 2022-07-24T20:13:40 | 2022-07-24T20:13:40 | 195,707,695 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package leetcode.string;
public class _680_ValidPalindromeII {
public boolean validPalindrome(String s) {
if ( s == null || s.length() <= 1) return true;
int l = 0, r = s.length() - 1;
char[] arr = s.toCharArray();
while (l <= r) {
if (arr[l] == arr[r]) {
l++;r--;
} else {
if (!isPalindrome(arr, l + 1, r) && !isPalindrome(arr, l, r - 1))
return false;
else
return true;
}
}
return true;
}
public boolean isPalindrome(char[] arr, int left, int right) {
int l = left, r = right;
while (l <= r) {
if (arr[l] != arr[r])
return false;
l++;
r--;
}
return true;
}
}
| UTF-8 | Java | 632 | java | _680_ValidPalindromeII.java | Java | [] | null | [] | package leetcode.string;
public class _680_ValidPalindromeII {
public boolean validPalindrome(String s) {
if ( s == null || s.length() <= 1) return true;
int l = 0, r = s.length() - 1;
char[] arr = s.toCharArray();
while (l <= r) {
if (arr[l] == arr[r]) {
l++;r--;
} else {
if (!isPalindrome(arr, l + 1, r) && !isPalindrome(arr, l, r - 1))
return false;
else
return true;
}
}
return true;
}
public boolean isPalindrome(char[] arr, int left, int right) {
int l = left, r = right;
while (l <= r) {
if (arr[l] != arr[r])
return false;
l++;
r--;
}
return true;
}
}
| 632 | 0.541139 | 0.528481 | 31 | 19.387096 | 17.597063 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3 | false | false | 9 |
ea14d7e78b5eda8741df8b90b3e03d1b9b108399 | 32,504,312,514,654 | 267ccb51333f528a50f2f8720fe989437596fd2b | /oncecloud-web-user/src/main/java/com/oncecloud/utils/AllocateHost.java | 98a6629e4d169488908f1a1caac2602d04ead61f | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | XJW163/OnceCloud | https://github.com/XJW163/OnceCloud | 55e393175b3073f94c074b2458b7cc25d7683081 | 7400154f41021704cd7eedec88489916b6d9eefb | refs/heads/master | 2021-05-30T05:28:44.261000 | 2015-12-22T12:07:43 | 2015-12-22T12:07:43 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* @author hty
* @time 上午11:17:28
* @date 2014年12月5日
*/
package com.oncecloud.utils;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Resource;
import org.springframework.stereotype.Component;
import org.Xen.API.Connection;
import org.Xen.API.Host;
import com.oncecloud.dao.HaDAO;
import com.oncecloud.dao.HostDAO;
import com.oncecloud.dao.UserDAO;
import com.oncecloud.dao.VMDAO;
import com.oncecloud.entity.OCHa;
import com.oncecloud.entity.OCHost;
import com.oncecloud.entity.User;
import com.oncecloud.model.performance.HaAccessPolicy;
@Component
public class AllocateHost {
private final static long MB = 1024 * 1024;
@Resource
private UserDAO userDAO;
@Resource
private HaDAO haDAO;
@Resource
private HostDAO hostDAO;
@Resource
private VMDAO vmDAO;
/**
* 获取空闲资源最大的连接池
* @param conn
* @param memory
* @return
*/
public String getAllocateHost(Connection conn, int memory, int userId) {
String host = null;
Set<Host> hostSet = null;
try {
Map<Host, Host.Record> hostMap = Host.getAllRecords(conn);
hostSet = getAviliableHost(hostMap, userId);
long maxFree = 0;
for (Host thisHost : hostSet) {
Host.Record hostRecord = hostMap.get(thisHost);
long memoryFree = hostRecord.memoryFree;
if (memoryFree > maxFree) {
maxFree = memoryFree;
host = thisHost.toWireString();
}
}
if ((int) (maxFree / MB) >= memory) {
return host;
} else {
return null;
}
} catch (Exception e) {
return null;
}
}
/**
* @author lining
* @param map
* HA为指定迁移主机的时候,把指定的主机去掉,获取可用的host资源
*/
private Set<Host> getAviliableHost(Map<Host, Host.Record> hostMap, int userId){
Set<Host> hostSet = null;
OCHa ha = haDAO.getHa(getPoolUuid(userId));
String[] migrateHostIds = null;
hostSet = hostMap.keySet();
if(ha != null){
if (ha.getAccessControlPolicy() == HaAccessPolicy.APPOINT_HOST) {
migrateHostIds = ha.getMigratoryHostUuid().split(",");
for (int i = 0; i < migrateHostIds.length; i++) {
for (Host leftHost : hostSet) {
if (leftHost.toWireString().equals(migrateHostIds[i])) {
hostSet.remove(leftHost);
}
}
}
}
}
return hostSet;
}
/**
* @author lining
* @param userid
* 高可用条件判断
*
*/
public boolean isHA(int userId, int memory){
OCHa ha = haDAO.getHa(getPoolUuid(userId));
List<OCHost> hostList = hostDAO.getHostListOfPool(getPoolUuid(userId));
if (ha == null) {
return true;
}else {
Integer accessPolicy = ha.getAccessControlPolicy();
if(accessPolicy == null){
return true;
}else {
int totalMem = getTotalMem(hostList);
int usedMem = memory;
int unUsedMem = totalMem - usedMem;
for (OCHost host : hostList) {
usedMem += vmDAO.getUsedMemByHostUuid(host.getHostUuid());
}
switch (accessPolicy) {
case HaAccessPolicy.LEFT_HOST_POLICY:
int lefthost = ha.getLeftHost();
int maxMem = getMaxMemOfHost(hostList, lefthost);
if (unUsedMem > maxMem) {
return true;
}else {
return false;
}
case HaAccessPolicy.PERCENT_POLICY:
if (unUsedMem > (totalMem * ha.getMemoryPercent())) {
return true;
}else {
return false;
}
case HaAccessPolicy.APPOINT_HOST:
int leftMem = getLeftMem(ha);
if (unUsedMem > leftMem) {
return true;
}else {
return false;
}
default:
return true;
}
}
}
}
/**
* @author lining
* @param userId
* 获取poolUuid
*
*/
private String getPoolUuid(int userId){
User user = userDAO.getUser(userId);
return user.getUserAllocate();
}
/**
* @author lining
* @param hostList
* 获取主机列表中的最大内存
*
*/
private int getMaxMemOfHost(List<OCHost> hosts, int lefthost){
Integer[] memArray = new Integer[hosts.size()];
for (int i = 0; i < memArray.length; i++) {
for (OCHost host : hosts) {
memArray[i] = host.getHostMem();
}
}
Arrays.sort(memArray, Collections.reverseOrder());
return maxMemOfHosts(memArray, lefthost);
}
/**
* @author lining
* @param lefthost
* 预留主机策略,根据预留主机数量计算预留的内存大小(默认主机内存按照从大到小排序)
*
*/
private int maxMemOfHosts(Integer[] memArray, int lefthost){
int maxMem = 0;
for (int j = 0; j < lefthost; j++) {
maxMem += memArray[j];
}
return maxMem;
}
/**
* @author lining
* @param ha
* 获取指定主机方案时剩余内存的大小
*
*/
private int getLeftMem(OCHa ha){
String migrateHostId = ha.getMigratoryHostUuid();
String[] migrateHostIds = migrateHostId.split(",");
int leftMem = 0;
for (int i = 0; i < migrateHostIds.length; i++) {
if (migrateHostIds[i].length() > 0) {
OCHost host = hostDAO.getHost(migrateHostIds[i]);
leftMem += host.getHostMem();
}
}
return leftMem;
}
/**
* @author lining
* @param hostlist
* 获取一个资源池内内存的大小
*/
private int getTotalMem(List<OCHost> hostLists){
int totalMem = 0;
if (hostLists != null) {
for (OCHost host : hostLists) {
totalMem += host.getHostMem();
}
}
return totalMem;
}
}
| UTF-8 | Java | 5,417 | java | AllocateHost.java | Java | [
{
"context": "/**\n * @author hty\n * @time 上午11:17:28\n * @date 2014年12月5日\n */\npacka",
"end": 18,
"score": 0.9996345043182373,
"start": 15,
"tag": "USERNAME",
"value": "hty"
},
{
"context": "ion e) {\n\t\t\treturn null;\n\t\t}\n\t}\n\t\n\t/**\n\t * @author lining\n\t * @param map\n\t * HA为指定迁移主机的时候,把指定的主机去掉,获取可用的hos",
"end": 1623,
"score": 0.994309663772583,
"start": 1617,
"tag": "USERNAME",
"value": "lining"
},
{
"context": "}\n\t\t\t}\n\t\t}\n\t\treturn hostSet;\n\t}\n\t\n\t/**\n\t * @author lining\n\t * @param userid\n\t * 高可用条件判断\n\t * \n\t */\n\tpublic b",
"end": 2312,
"score": 0.9880689382553101,
"start": 2306,
"tag": "USERNAME",
"value": "lining"
},
{
"context": "urn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t}\n\t}\n\t\n\t/**\n\t * @author lining\n\t * @param userId\n\t * 获取poolUuid\n\t * \n\t */\n\tpriva",
"end": 3543,
"score": 0.5948945879936218,
"start": 3537,
"tag": "USERNAME",
"value": "lining"
},
{
"context": "turn user.getUserAllocate();\n\t}\n\t\n\t/**\n\t * @author lining\n\t * @param hostList\n\t * 获取主机列表中的最大内存\n\t * \n\t */",
"end": 3725,
"score": 0.5146333575248718,
"start": 3722,
"tag": "NAME",
"value": "lin"
},
{
"context": " user.getUserAllocate();\n\t}\n\t\n\t/**\n\t * @author lining\n\t * @param hostList\n\t * 获取主机列表中的最大内存\n\t * \n\t */\n ",
"end": 3728,
"score": 0.5760140419006348,
"start": 3725,
"tag": "USERNAME",
"value": "ing"
},
{
"context": "emArray, lefthost);\n }\n\t\n /**\n * @author lining\n * @param lefthost\n * 预留主机策略,根据预留主机数量计算预留",
"end": 4165,
"score": 0.5997768640518188,
"start": 4159,
"tag": "USERNAME",
"value": "lining"
},
{
"context": ";\n\t\t}\n\t\treturn maxMem;\n }\n \n\t/**\n\t * @author lining\n\t * @param ha\n\t * 获取指定主机方案时剩余内存的大小\n\t * \n\t */\n\tpri",
"end": 4462,
"score": 0.8272334337234497,
"start": 4456,
"tag": "USERNAME",
"value": "lining"
},
{
"context": ";\n\t\t\t}\n\t\t}\n\t\treturn leftMem;\n\t}\n\t\n\t/**\n\t * @author lining\n\t * @param hostlist\n\t * 获取一个资源池内内存的大小\n\t */\n\tpriva",
"end": 4903,
"score": 0.961730420589447,
"start": 4897,
"tag": "USERNAME",
"value": "lining"
}
] | null | [] | /**
* @author hty
* @time 上午11:17:28
* @date 2014年12月5日
*/
package com.oncecloud.utils;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Resource;
import org.springframework.stereotype.Component;
import org.Xen.API.Connection;
import org.Xen.API.Host;
import com.oncecloud.dao.HaDAO;
import com.oncecloud.dao.HostDAO;
import com.oncecloud.dao.UserDAO;
import com.oncecloud.dao.VMDAO;
import com.oncecloud.entity.OCHa;
import com.oncecloud.entity.OCHost;
import com.oncecloud.entity.User;
import com.oncecloud.model.performance.HaAccessPolicy;
@Component
public class AllocateHost {
private final static long MB = 1024 * 1024;
@Resource
private UserDAO userDAO;
@Resource
private HaDAO haDAO;
@Resource
private HostDAO hostDAO;
@Resource
private VMDAO vmDAO;
/**
* 获取空闲资源最大的连接池
* @param conn
* @param memory
* @return
*/
public String getAllocateHost(Connection conn, int memory, int userId) {
String host = null;
Set<Host> hostSet = null;
try {
Map<Host, Host.Record> hostMap = Host.getAllRecords(conn);
hostSet = getAviliableHost(hostMap, userId);
long maxFree = 0;
for (Host thisHost : hostSet) {
Host.Record hostRecord = hostMap.get(thisHost);
long memoryFree = hostRecord.memoryFree;
if (memoryFree > maxFree) {
maxFree = memoryFree;
host = thisHost.toWireString();
}
}
if ((int) (maxFree / MB) >= memory) {
return host;
} else {
return null;
}
} catch (Exception e) {
return null;
}
}
/**
* @author lining
* @param map
* HA为指定迁移主机的时候,把指定的主机去掉,获取可用的host资源
*/
private Set<Host> getAviliableHost(Map<Host, Host.Record> hostMap, int userId){
Set<Host> hostSet = null;
OCHa ha = haDAO.getHa(getPoolUuid(userId));
String[] migrateHostIds = null;
hostSet = hostMap.keySet();
if(ha != null){
if (ha.getAccessControlPolicy() == HaAccessPolicy.APPOINT_HOST) {
migrateHostIds = ha.getMigratoryHostUuid().split(",");
for (int i = 0; i < migrateHostIds.length; i++) {
for (Host leftHost : hostSet) {
if (leftHost.toWireString().equals(migrateHostIds[i])) {
hostSet.remove(leftHost);
}
}
}
}
}
return hostSet;
}
/**
* @author lining
* @param userid
* 高可用条件判断
*
*/
public boolean isHA(int userId, int memory){
OCHa ha = haDAO.getHa(getPoolUuid(userId));
List<OCHost> hostList = hostDAO.getHostListOfPool(getPoolUuid(userId));
if (ha == null) {
return true;
}else {
Integer accessPolicy = ha.getAccessControlPolicy();
if(accessPolicy == null){
return true;
}else {
int totalMem = getTotalMem(hostList);
int usedMem = memory;
int unUsedMem = totalMem - usedMem;
for (OCHost host : hostList) {
usedMem += vmDAO.getUsedMemByHostUuid(host.getHostUuid());
}
switch (accessPolicy) {
case HaAccessPolicy.LEFT_HOST_POLICY:
int lefthost = ha.getLeftHost();
int maxMem = getMaxMemOfHost(hostList, lefthost);
if (unUsedMem > maxMem) {
return true;
}else {
return false;
}
case HaAccessPolicy.PERCENT_POLICY:
if (unUsedMem > (totalMem * ha.getMemoryPercent())) {
return true;
}else {
return false;
}
case HaAccessPolicy.APPOINT_HOST:
int leftMem = getLeftMem(ha);
if (unUsedMem > leftMem) {
return true;
}else {
return false;
}
default:
return true;
}
}
}
}
/**
* @author lining
* @param userId
* 获取poolUuid
*
*/
private String getPoolUuid(int userId){
User user = userDAO.getUser(userId);
return user.getUserAllocate();
}
/**
* @author lining
* @param hostList
* 获取主机列表中的最大内存
*
*/
private int getMaxMemOfHost(List<OCHost> hosts, int lefthost){
Integer[] memArray = new Integer[hosts.size()];
for (int i = 0; i < memArray.length; i++) {
for (OCHost host : hosts) {
memArray[i] = host.getHostMem();
}
}
Arrays.sort(memArray, Collections.reverseOrder());
return maxMemOfHosts(memArray, lefthost);
}
/**
* @author lining
* @param lefthost
* 预留主机策略,根据预留主机数量计算预留的内存大小(默认主机内存按照从大到小排序)
*
*/
private int maxMemOfHosts(Integer[] memArray, int lefthost){
int maxMem = 0;
for (int j = 0; j < lefthost; j++) {
maxMem += memArray[j];
}
return maxMem;
}
/**
* @author lining
* @param ha
* 获取指定主机方案时剩余内存的大小
*
*/
private int getLeftMem(OCHa ha){
String migrateHostId = ha.getMigratoryHostUuid();
String[] migrateHostIds = migrateHostId.split(",");
int leftMem = 0;
for (int i = 0; i < migrateHostIds.length; i++) {
if (migrateHostIds[i].length() > 0) {
OCHost host = hostDAO.getHost(migrateHostIds[i]);
leftMem += host.getHostMem();
}
}
return leftMem;
}
/**
* @author lining
* @param hostlist
* 获取一个资源池内内存的大小
*/
private int getTotalMem(List<OCHost> hostLists){
int totalMem = 0;
if (hostLists != null) {
for (OCHost host : hostLists) {
totalMem += host.getHostMem();
}
}
return totalMem;
}
}
| 5,417 | 0.644009 | 0.638182 | 228 | 21.574562 | 18.060053 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.45614 | false | false | 9 |
698377a3d751be78b37df24f9c826869909f08ca | 23,373,212,045,483 | 6085a05ec7c011c70fc09f105a1acc93a2bf9ce8 | /src/main/java/com/gbicc/shibeikeapp/service/impl/SysuserServiceImpl.java | bc18a461452c34d6003fb7bb2efb02656099ac78 | [] | no_license | weiaiwan/shibeikeapp | https://github.com/weiaiwan/shibeikeapp | e0b11dc01d05a9e8139444857315206cca6ed8f0 | 69d06ff12f0c61bd10104375e4290935cfbed88c | refs/heads/master | 2021-05-10T12:40:48.256000 | 2018-01-22T11:30:22 | 2018-01-22T11:30:22 | 118,448,456 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Powered By [easy_project]
* Since 2010 - 2015
*/
package com.gbicc.shibeikeapp.service.impl;
import com.gbicc.shibeikeapp.dao.SysUserTabDao;
import com.gbicc.shibeikeapp.entity.SysPostTab;
import com.gbicc.shibeikeapp.entity.SysUserTab;
import com.gbicc.shibeikeapp.service.SysuserService;
import com.gbicc.shibeikeapp.utils.MD5Util;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
/**
* @author easyloan
* @version 1.0
* @since 1.0
*/
@Service(value="sysuserService")
public class SysuserServiceImpl implements SysuserService {
/**增加@Resource注解,spring就可以通过autowire自动设置对象属性,请注意大小写*/
@Resource
private SysUserTabDao sysUserTabDao;
public void setSysUserTabDao(SysUserTabDao sysUserTabDao) {
this.sysUserTabDao = sysUserTabDao;
}
@Override
public void insertSysUser(SysUserTab sysUserTab) {
if (sysUserTab != null) {
sysUserTab.setUserPass(MD5Util.getMD5("123456"));
}
Integer sort = sysUserTabDao.getMaxSorting() + 1;
sysUserTab.setSorting(sort.toString());
sysUserTabDao.insertSysUser(sysUserTab);
}
@Override
public void updateSysUser(SysUserTab sysUserTab) {
sysUserTabDao.updateSysUser(sysUserTab);
}
@Override
public void deleteSysUser(String id) {
sysUserTabDao.deleteSysUser(id);
}
@Override
public List<SysUserTab> getSysUser(Map<String, Object> map) {
return sysUserTabDao.getSysUser(map);
}
@Override
public SysUserTab getSysUserById(String id) {
return sysUserTabDao.getSysUserById(id);
}
@Override
public Integer getCount(Map<String, Object> map) {
return sysUserTabDao.getCount(map);
}
@Override
public SysUserTab login(SysUserTab sysUserTab) {
return sysUserTabDao.login(sysUserTab);
}
@Override
public void updatePwd(SysUserTab sysUserTab) {
sysUserTabDao.reSetPwd(sysUserTab);
}
@Override
public List<SysUserTab> getUserByPost(SysPostTab post) {
return sysUserTabDao.getUserByPost(post);
}
@Override
public void updaateSortingByEdit(Integer sorting) {
sysUserTabDao.updaateSortingByEdit(sorting);
}
@Override
public void updaateSortingByDel(Integer sorting) {
sysUserTabDao.updaateSortingByDel(sorting);
}
@Override
public void updateSession(SysUserTab sysUserTab) {
// TODO Auto-generated method stub
sysUserTabDao.updateSession(sysUserTab);
}
@Override
public void updateSession1(String id) {
// TODO Auto-generated method stub
sysUserTabDao.updateSession1(id);
}
@Override
public List<SysUserTab> getUserNP(Map<String, Object> map) {
// TODO Auto-generated method stub
return sysUserTabDao.getUserNP(map);
}
@Override
public SysUserTab selectloginName(String loginName) {
// TODO Auto-generated method stub
return sysUserTabDao.selectloginName(loginName);
}
@Override
public void updateWrongCount(SysUserTab sysUserTab) {
// TODO Auto-generated method stub
sysUserTabDao.updateWrongCount(sysUserTab);
}
@Override
public void updateWrongCount0(SysUserTab sysUserTab) {
// TODO Auto-generated method stub
sysUserTabDao.updateWrongCount0(sysUserTab);
}
@Override
public Integer getUserLoginName(String loginName) {
// TODO Auto-generated method stub
return sysUserTabDao.getUserLoginName(loginName);
}
@Override
public void insertSysUser2(SysUserTab sysUserTab) {
// TODO Auto-generated method stub
Integer sort = sysUserTabDao.getMaxSorting() + 1;
sysUserTab.setSorting(sort.toString());
sysUserTabDao.insertSysUser(sysUserTab);
}
}
| UTF-8 | Java | 3,551 | java | SysuserServiceImpl.java | Java | [
{
"context": ".util.List;\nimport java.util.Map;\n\n\n/**\n * @author easyloan \n * @version 1.0\n * @since 1.0\n */\n\n@Service(valu",
"end": 496,
"score": 0.999579906463623,
"start": 488,
"tag": "USERNAME",
"value": "easyloan"
},
{
"context": "null) {\n\t\t\tsysUserTab.setUserPass(MD5Util.getMD5(\"123456\"));\n\t\t}\n\t\tInteger sort = sysUserTabDao.getMaxSort",
"end": 974,
"score": 0.9931514263153076,
"start": 968,
"tag": "PASSWORD",
"value": "123456"
}
] | null | [] | /*
* Powered By [easy_project]
* Since 2010 - 2015
*/
package com.gbicc.shibeikeapp.service.impl;
import com.gbicc.shibeikeapp.dao.SysUserTabDao;
import com.gbicc.shibeikeapp.entity.SysPostTab;
import com.gbicc.shibeikeapp.entity.SysUserTab;
import com.gbicc.shibeikeapp.service.SysuserService;
import com.gbicc.shibeikeapp.utils.MD5Util;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
/**
* @author easyloan
* @version 1.0
* @since 1.0
*/
@Service(value="sysuserService")
public class SysuserServiceImpl implements SysuserService {
/**增加@Resource注解,spring就可以通过autowire自动设置对象属性,请注意大小写*/
@Resource
private SysUserTabDao sysUserTabDao;
public void setSysUserTabDao(SysUserTabDao sysUserTabDao) {
this.sysUserTabDao = sysUserTabDao;
}
@Override
public void insertSysUser(SysUserTab sysUserTab) {
if (sysUserTab != null) {
sysUserTab.setUserPass(MD5Util.getMD5("<PASSWORD>"));
}
Integer sort = sysUserTabDao.getMaxSorting() + 1;
sysUserTab.setSorting(sort.toString());
sysUserTabDao.insertSysUser(sysUserTab);
}
@Override
public void updateSysUser(SysUserTab sysUserTab) {
sysUserTabDao.updateSysUser(sysUserTab);
}
@Override
public void deleteSysUser(String id) {
sysUserTabDao.deleteSysUser(id);
}
@Override
public List<SysUserTab> getSysUser(Map<String, Object> map) {
return sysUserTabDao.getSysUser(map);
}
@Override
public SysUserTab getSysUserById(String id) {
return sysUserTabDao.getSysUserById(id);
}
@Override
public Integer getCount(Map<String, Object> map) {
return sysUserTabDao.getCount(map);
}
@Override
public SysUserTab login(SysUserTab sysUserTab) {
return sysUserTabDao.login(sysUserTab);
}
@Override
public void updatePwd(SysUserTab sysUserTab) {
sysUserTabDao.reSetPwd(sysUserTab);
}
@Override
public List<SysUserTab> getUserByPost(SysPostTab post) {
return sysUserTabDao.getUserByPost(post);
}
@Override
public void updaateSortingByEdit(Integer sorting) {
sysUserTabDao.updaateSortingByEdit(sorting);
}
@Override
public void updaateSortingByDel(Integer sorting) {
sysUserTabDao.updaateSortingByDel(sorting);
}
@Override
public void updateSession(SysUserTab sysUserTab) {
// TODO Auto-generated method stub
sysUserTabDao.updateSession(sysUserTab);
}
@Override
public void updateSession1(String id) {
// TODO Auto-generated method stub
sysUserTabDao.updateSession1(id);
}
@Override
public List<SysUserTab> getUserNP(Map<String, Object> map) {
// TODO Auto-generated method stub
return sysUserTabDao.getUserNP(map);
}
@Override
public SysUserTab selectloginName(String loginName) {
// TODO Auto-generated method stub
return sysUserTabDao.selectloginName(loginName);
}
@Override
public void updateWrongCount(SysUserTab sysUserTab) {
// TODO Auto-generated method stub
sysUserTabDao.updateWrongCount(sysUserTab);
}
@Override
public void updateWrongCount0(SysUserTab sysUserTab) {
// TODO Auto-generated method stub
sysUserTabDao.updateWrongCount0(sysUserTab);
}
@Override
public Integer getUserLoginName(String loginName) {
// TODO Auto-generated method stub
return sysUserTabDao.getUserLoginName(loginName);
}
@Override
public void insertSysUser2(SysUserTab sysUserTab) {
// TODO Auto-generated method stub
Integer sort = sysUserTabDao.getMaxSorting() + 1;
sysUserTab.setSorting(sort.toString());
sysUserTabDao.insertSysUser(sysUserTab);
}
}
| 3,555 | 0.770899 | 0.76291 | 148 | 22.682432 | 21.068434 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.195946 | false | false | 9 |
6c7ff5ba80f45b3f312e426e73a7afbc52a3f676 | 33,629,593,943,696 | 5ecd15baa833422572480fad3946e0e16a389000 | /framework/DeviceRepository-Open/subsystems/repository/main/impl/java/com/volantis/devrep/repository/impl/devices/category/DefaultCategoryDescriptor.java | f29662fef5937687938b3c3b92c93d22f67aaa99 | [] | no_license | jabley/volmobserverce | https://github.com/jabley/volmobserverce | 4c5db36ef72c3bb7ef20fb81855e18e9b53823b9 | 6d760f27ac5917533eca6708f389ed9347c7016d | refs/heads/master | 2021-01-01T05:31:21.902000 | 2009-02-04T02:29:06 | 2009-02-04T02:29:06 | 38,675,289 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
This file is part of Volantis Mobility Server.
Volantis Mobility Server is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Volantis Mobility Server is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Volantis Mobility Server. If not, see <http://www.gnu.org/licenses/>.
*/
/* ----------------------------------------------------------------------------
* (c) Volantis Systems Ltd 2004.
* ----------------------------------------------------------------------------
*/
package com.volantis.devrep.repository.impl.devices.category;
import com.volantis.mcs.devices.category.CategoryDescriptor;
/**
* Default implementation of {@link CategoryDescriptor}.
*/
public class DefaultCategoryDescriptor implements CategoryDescriptor {
/**
* The descriptive name of the category.
* <p>
* NOTE: this is currently null if this category descriptor was created from
* a JDBC repository, since JDBC does not currently store this information.
*/
private String categoryDescriptiveName;
/**
* Language of the descriptive name.
*/
private String language;
/**
* Set the descriptive name for this descriptor.
*
* @param categoryDescriptiveName the descriptive name for this descriptor.
* @see #categoryDescriptiveName
*/
public void setCategoryDescriptiveName(final String categoryDescriptiveName) {
this.categoryDescriptiveName = categoryDescriptiveName;
}
// Javadoc inherited.
public String getCategoryDescriptiveName() {
return categoryDescriptiveName;
}
// Javadoc inherited.
public String toString() {
// This unusual format is so we can diff the output and also to
// make it a bit more readable.
return "[DefaultCategoryDescriptor:" +
" descriptiveName=" + categoryDescriptiveName + " ]";
}
/**
* Sets the language.
*
* @param language the new language value
*/
public void setLanguage(final String language) {
this.language = language;
}
// javadoc inherited
public String getLanguage() {
return language;
}
}
/*
===========================================================================
Change History
===========================================================================
$Log$
===========================================================================
*/
| UTF-8 | Java | 2,839 | java | DefaultCategoryDescriptor.java | Java | [] | null | [] | /*
This file is part of Volantis Mobility Server.
Volantis Mobility Server is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Volantis Mobility Server is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Volantis Mobility Server. If not, see <http://www.gnu.org/licenses/>.
*/
/* ----------------------------------------------------------------------------
* (c) Volantis Systems Ltd 2004.
* ----------------------------------------------------------------------------
*/
package com.volantis.devrep.repository.impl.devices.category;
import com.volantis.mcs.devices.category.CategoryDescriptor;
/**
* Default implementation of {@link CategoryDescriptor}.
*/
public class DefaultCategoryDescriptor implements CategoryDescriptor {
/**
* The descriptive name of the category.
* <p>
* NOTE: this is currently null if this category descriptor was created from
* a JDBC repository, since JDBC does not currently store this information.
*/
private String categoryDescriptiveName;
/**
* Language of the descriptive name.
*/
private String language;
/**
* Set the descriptive name for this descriptor.
*
* @param categoryDescriptiveName the descriptive name for this descriptor.
* @see #categoryDescriptiveName
*/
public void setCategoryDescriptiveName(final String categoryDescriptiveName) {
this.categoryDescriptiveName = categoryDescriptiveName;
}
// Javadoc inherited.
public String getCategoryDescriptiveName() {
return categoryDescriptiveName;
}
// Javadoc inherited.
public String toString() {
// This unusual format is so we can diff the output and also to
// make it a bit more readable.
return "[DefaultCategoryDescriptor:" +
" descriptiveName=" + categoryDescriptiveName + " ]";
}
/**
* Sets the language.
*
* @param language the new language value
*/
public void setLanguage(final String language) {
this.language = language;
}
// javadoc inherited
public String getLanguage() {
return language;
}
}
/*
===========================================================================
Change History
===========================================================================
$Log$
===========================================================================
*/
| 2,839 | 0.604159 | 0.602397 | 88 | 31.238636 | 29.061453 | 82 | false | false | 0 | 0 | 0 | 0 | 76 | 0.080367 | 0.170455 | false | false | 9 |
aa05c2ecac8b80e236e683db3b89897736ace35f | 13,563,506,742,800 | 4adc1e0ec1e4342fb9f5fdc4ca56e5a1472989ef | /light-util/src/main/java/com/zxg/light/util/string/StringUtil.java | e43e260bc133146c4a83b80fdbb6ab0bc7838879 | [] | no_license | Xianguang/light-util | https://github.com/Xianguang/light-util | dcc6e07c13631841986846c5440acce7b27a81f0 | 24e582d27d04340e0dd61876ab1da6a196159ad9 | refs/heads/master | 2018-12-31T21:13:53.914000 | 2012-12-22T05:03:52 | 2012-12-22T05:03:52 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.zxg.light.util.string;
/**
*
* @author Xianguang Zhou
*
*/
public class StringUtil {
public static String[] toArray(String s, int n) {
String[] array = new String[n];
for (int i = 0; i < n; i++) {
array[i] = s;
}
return array;
}
}
| UTF-8 | Java | 262 | java | StringUtil.java | Java | [
{
"context": "age com.zxg.light.util.string;\n\n/**\n * \n * @author Xianguang Zhou\n *\n */\npublic class StringUtil {\n\tpublic static S",
"end": 69,
"score": 0.9998255372047424,
"start": 55,
"tag": "NAME",
"value": "Xianguang Zhou"
}
] | null | [] | package com.zxg.light.util.string;
/**
*
* @author <NAME>
*
*/
public class StringUtil {
public static String[] toArray(String s, int n) {
String[] array = new String[n];
for (int i = 0; i < n; i++) {
array[i] = s;
}
return array;
}
}
| 254 | 0.587786 | 0.583969 | 16 | 15.375 | 15.206392 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.25 | false | false | 9 |
6330bae1d589a51386129bc10e9d0a94605e25bb | 14,757,507,644,922 | 2276449dce905315f206d2075a1b726aab680181 | /src/main/java/com/ehaqui/lib/menu/items/Button.java | 0e468cb19f5e9d1bf68dca1d683fb288c2ecb229 | [] | no_license | lucasdidur/EhLib | https://github.com/lucasdidur/EhLib | 5d1fa859d16e63e6aba1d1af900b736b5a48a8e7 | 9038e7fb8adc26cb5d1d279908413736e84b3ed7 | refs/heads/master | 2021-01-20T03:07:01.783000 | 2017-05-01T00:00:47 | 2017-05-01T00:00:47 | 88,438,615 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* This file is part of AmpMenus.
*
* Copyright (c) 2014 <http://github.com/ampayne2/AmpMenus/>
*
* AmpMenus is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* AmpMenus is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with AmpMenus. If not, see <http://www.gnu.org/licenses/>.
*/
package com.ehaqui.lib.menu.items;
import com.ehaqui.lib.gui.anvil.AnvilClickEventHandler;
import com.ehaqui.lib.gui.anvil.AnvilGui;
import com.ehaqui.lib.gui.anvil.AnvilSlot;
import com.ehaqui.lib.menu.events.ItemClickEvent;
import com.ehaqui.lib.menu.exceptions.MenuException;
import com.ehaqui.lib.menu.menus.Menu;
import com.ehaqui.lib.message.Message;
import com.ehaqui.lib.util.ItemUtils;
import lombok.Getter;
import lombok.Setter;
import org.bukkit.*;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.SkullMeta;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
/**
* An Item inside an {@link com.ehaqui.lib.menu.menus.Menu}.
*
* @param <T>
*/
@Getter
@Setter
public abstract class Button<T>
{
private JavaPlugin plugin;
private String displayName = "";
private ItemStack icon = new ItemStack(Material.STAINED_GLASS_PANE);
private List<String> lore = new ArrayList<>();
private UUID uuid;
private T option;
public Button()
{
setName("");
lore.clear();
}
public Button(Material material)
{
setName("");
setIcon(material);
}
public Button(ItemStack item)
{
setItem(item);
}
@SuppressWarnings("deprecation")
public Button(String displayName)
{
setName(displayName);
setIcon(new ItemStack(Material.STAINED_GLASS_PANE, 1, (short) 7));
}
public Button(String displayName, ItemStack icon)
{
setName(displayName);
setIcon(icon);
}
public Button(String displayName, ItemStack icon, String... lore)
{
setName(displayName);
setIcon(icon);
setLore(lore);
}
public Player getPlayer()
{
return Bukkit.getPlayer(getUuid());
}
public void setPlayer(Player player)
{
this.uuid = player.getUniqueId();
}
public OfflinePlayer getPlayerOffline()
{
return Bukkit.getOfflinePlayer(getUuid());
}
/**
* Sets the display name and lore of an ItemStack.
*
* @param itemStack The ItemStack.
* @param displayName The display name.
* @param lore The lore.
* @return The ItemStack.
*/
public static ItemStack setNameAndLore(ItemStack itemStack, String displayName, List<String> lore)
{
if (itemStack.getType() != Material.AIR)
{
ItemMeta meta = itemStack.getItemMeta();
meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', displayName));
List<String> lores = new ArrayList<String>();
if (lore != null)
{
for (String lor : lore)
{
lores.add(ChatColor.translateAlternateColorCodes('&', lor));
}
}
meta.setLore(lores);
itemStack.setItemMeta(meta);
}
return itemStack;
}
public Button<T> setUuid(UUID uuid)
{
this.uuid = uuid;
return this;
}
public Button<T> setOption(T option)
{
this.option = option;
return this;
}
public Button<T> setName(String displayName, Object... args)
{
this.displayName = ChatColor.translateAlternateColorCodes('&', "&r" + String.format(displayName, args));
return this;
}
public Button<T> setTitle(String displayName, Object... args)
{
setName(displayName, args);
return this;
}
public Button<T> setIcon(ItemStack icon)
{
if (icon != null)
{
ItemMeta im = icon.getItemMeta();
im.addItemFlags(ItemFlag.HIDE_ATTRIBUTES, ItemFlag.HIDE_PLACED_ON, ItemFlag.HIDE_UNBREAKABLE);
icon.setItemMeta(im);
this.icon = icon;
}
return this;
}
public Button<T> setIconTexture(String texture)
{
setIcon(ItemUtils.getSkull(texture));
return this;
}
public Button<T> setIcon(String itemString)
{
setIcon(ItemUtils.parseItem(itemString));
return this;
}
public Button<T> setIcon(Material material)
{
this.icon.setType(material);
return this;
}
public Button<T> setHeadOwner(String owner)
{
setIcon(new ItemStack(Material.SKULL_ITEM, 1, (short) SkullType.PLAYER.ordinal()));
SkullMeta sm = (SkullMeta) getIcon().getItemMeta();
sm.setOwner(owner);
getIcon().setItemMeta(sm);
return this;
}
public Button<T> setMaterial(Material material)
{
this.icon.setType(material);
return this;
}
public Button<T> addLore(String lore, Object... args)
{
for (String string: lore.split("\n"))
{
this.lore.add(ChatColor.translateAlternateColorCodes('&', "&r" + String.format(string, args)).replace("\r", ""));
}
return this;
}
public Button<T> setLore(String... lore)
{
setLore(Arrays.asList(lore));
return this;
}
public Button<T> setLore(List<String> lore)
{
this.lore.clear();
for (String string : lore)
{
addLore(string);
}
return this;
}
public void openMenu(Class<? extends Menu> clazz, ItemClickEvent event)
{
openMenu(clazz, event, null);
}
public <R> void openMenu(Class<? extends Menu> clazz, ItemClickEvent event, R option)
{
try
{
Menu menu = clazz.newInstance();
if (option == null)
menu.setOption(getOption());
else
menu.setOption(option);
menu.setParent(event);
menu.setPlugin(getPlugin());
menu.setUuid(getUuid());
menu.open(event.getPlayer());
event.setWillOpenMenu(true);
} catch (InstantiationException | IllegalAccessException e)
{
e.printStackTrace();
}
}
/**
* Gets the ItemStack to be shown to the player.
*
* @param player The player.
* @return The final icon.
*/
public ItemStack getFinalIcon(Player player)
{
return setNameAndLore(getIcon().clone(), getDisplayName(), getLore());
}
/**
* Called when the ItemMenu<T> is clicked.
*
* @param event The {@link com.ehaqui.lib.menu.events.ItemClickEvent}.
*/
public abstract void onItemClick(ItemClickEvent event) throws MenuException;
public void process(String text) throws MenuException
{
}
/**
* Sets the current item;
*
* @param item
*/
public Button<T> setItem(ItemStack item)
{
this.icon = item;
if (item.getType() != Material.AIR)
{
if (item.getItemMeta().hasDisplayName())
this.displayName = item.getItemMeta().getDisplayName();
else
this.displayName = "";
if (item.getItemMeta().hasLore())
this.lore = item.getItemMeta().getLore();
else
this.lore = new ArrayList<>();
}
return this;
}
public void getText(ItemClickEvent event, String text, boolean back, String... lore)
{
getText(event, text, new ItemStack(Material.EMERALD_BLOCK), back, lore);
}
public void getText(ItemClickEvent event, String text, String... lore)
{
getText(event, text, new ItemStack(Material.EMERALD_BLOCK), lore);
}
public void getText(ItemClickEvent event, String text, ItemStack icon, String... lore)
{
getText(event, text, icon, true, lore);
}
public void getText(ItemClickEvent event, String text, ItemStack icon, boolean back, String... lore)
{
new BukkitRunnable()
{
@Override
public void run()
{
AnvilGui gui = new AnvilGui(event.getPlayer(), (AnvilClickEventHandler) event2 ->
{
boolean error = false;
if (event2.getSlot() == AnvilSlot.OUTPUT)
{
try
{
process(event2.getText());
} catch (MenuException ex)
{
send("&c" + ex.getMessage());
error = true;
}
}
if (back || error)
{
new BukkitRunnable()
{
@Override
public void run()
{
Menu menu = event.getMenu();
if (menu.getPlugin() == null)
menu.setPlugin(getPlugin());
menu.setUuid(getUuid());
menu.open(event.getPlayer());
}
}.runTaskLater(getPlugin(), 3);
}
event.setWillClose(true);
}, getPlugin());
gui.setSlot(AnvilSlot.INPUT_LEFT, text, icon, lore);
gui.open();
}
}.runTaskLater(getPlugin(), 3);
event.setWillClose(true);
}
public void send(String message)
{
Message.send(getPlayer(), message);
}
public void send(Message.Type type, String... message)
{
if (message.length > 1)
Message.send(type, getPlayer(), message[0], message[1]);
else
Message.send(type, getPlayer(), message[0]);
}
}
| UTF-8 | Java | 10,715 | java | Button.java | Java | [
{
"context": "enus.\n *\n * Copyright (c) 2014 <http://github.com/ampayne2/AmpMenus/>\n *\n * AmpMenus is free software: you c",
"end": 89,
"score": 0.9995052218437195,
"start": 81,
"tag": "USERNAME",
"value": "ampayne2"
}
] | null | [] | /*
* This file is part of AmpMenus.
*
* Copyright (c) 2014 <http://github.com/ampayne2/AmpMenus/>
*
* AmpMenus is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* AmpMenus is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with AmpMenus. If not, see <http://www.gnu.org/licenses/>.
*/
package com.ehaqui.lib.menu.items;
import com.ehaqui.lib.gui.anvil.AnvilClickEventHandler;
import com.ehaqui.lib.gui.anvil.AnvilGui;
import com.ehaqui.lib.gui.anvil.AnvilSlot;
import com.ehaqui.lib.menu.events.ItemClickEvent;
import com.ehaqui.lib.menu.exceptions.MenuException;
import com.ehaqui.lib.menu.menus.Menu;
import com.ehaqui.lib.message.Message;
import com.ehaqui.lib.util.ItemUtils;
import lombok.Getter;
import lombok.Setter;
import org.bukkit.*;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.SkullMeta;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
/**
* An Item inside an {@link com.ehaqui.lib.menu.menus.Menu}.
*
* @param <T>
*/
@Getter
@Setter
public abstract class Button<T>
{
private JavaPlugin plugin;
private String displayName = "";
private ItemStack icon = new ItemStack(Material.STAINED_GLASS_PANE);
private List<String> lore = new ArrayList<>();
private UUID uuid;
private T option;
public Button()
{
setName("");
lore.clear();
}
public Button(Material material)
{
setName("");
setIcon(material);
}
public Button(ItemStack item)
{
setItem(item);
}
@SuppressWarnings("deprecation")
public Button(String displayName)
{
setName(displayName);
setIcon(new ItemStack(Material.STAINED_GLASS_PANE, 1, (short) 7));
}
public Button(String displayName, ItemStack icon)
{
setName(displayName);
setIcon(icon);
}
public Button(String displayName, ItemStack icon, String... lore)
{
setName(displayName);
setIcon(icon);
setLore(lore);
}
public Player getPlayer()
{
return Bukkit.getPlayer(getUuid());
}
public void setPlayer(Player player)
{
this.uuid = player.getUniqueId();
}
public OfflinePlayer getPlayerOffline()
{
return Bukkit.getOfflinePlayer(getUuid());
}
/**
* Sets the display name and lore of an ItemStack.
*
* @param itemStack The ItemStack.
* @param displayName The display name.
* @param lore The lore.
* @return The ItemStack.
*/
public static ItemStack setNameAndLore(ItemStack itemStack, String displayName, List<String> lore)
{
if (itemStack.getType() != Material.AIR)
{
ItemMeta meta = itemStack.getItemMeta();
meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', displayName));
List<String> lores = new ArrayList<String>();
if (lore != null)
{
for (String lor : lore)
{
lores.add(ChatColor.translateAlternateColorCodes('&', lor));
}
}
meta.setLore(lores);
itemStack.setItemMeta(meta);
}
return itemStack;
}
public Button<T> setUuid(UUID uuid)
{
this.uuid = uuid;
return this;
}
public Button<T> setOption(T option)
{
this.option = option;
return this;
}
public Button<T> setName(String displayName, Object... args)
{
this.displayName = ChatColor.translateAlternateColorCodes('&', "&r" + String.format(displayName, args));
return this;
}
public Button<T> setTitle(String displayName, Object... args)
{
setName(displayName, args);
return this;
}
public Button<T> setIcon(ItemStack icon)
{
if (icon != null)
{
ItemMeta im = icon.getItemMeta();
im.addItemFlags(ItemFlag.HIDE_ATTRIBUTES, ItemFlag.HIDE_PLACED_ON, ItemFlag.HIDE_UNBREAKABLE);
icon.setItemMeta(im);
this.icon = icon;
}
return this;
}
public Button<T> setIconTexture(String texture)
{
setIcon(ItemUtils.getSkull(texture));
return this;
}
public Button<T> setIcon(String itemString)
{
setIcon(ItemUtils.parseItem(itemString));
return this;
}
public Button<T> setIcon(Material material)
{
this.icon.setType(material);
return this;
}
public Button<T> setHeadOwner(String owner)
{
setIcon(new ItemStack(Material.SKULL_ITEM, 1, (short) SkullType.PLAYER.ordinal()));
SkullMeta sm = (SkullMeta) getIcon().getItemMeta();
sm.setOwner(owner);
getIcon().setItemMeta(sm);
return this;
}
public Button<T> setMaterial(Material material)
{
this.icon.setType(material);
return this;
}
public Button<T> addLore(String lore, Object... args)
{
for (String string: lore.split("\n"))
{
this.lore.add(ChatColor.translateAlternateColorCodes('&', "&r" + String.format(string, args)).replace("\r", ""));
}
return this;
}
public Button<T> setLore(String... lore)
{
setLore(Arrays.asList(lore));
return this;
}
public Button<T> setLore(List<String> lore)
{
this.lore.clear();
for (String string : lore)
{
addLore(string);
}
return this;
}
public void openMenu(Class<? extends Menu> clazz, ItemClickEvent event)
{
openMenu(clazz, event, null);
}
public <R> void openMenu(Class<? extends Menu> clazz, ItemClickEvent event, R option)
{
try
{
Menu menu = clazz.newInstance();
if (option == null)
menu.setOption(getOption());
else
menu.setOption(option);
menu.setParent(event);
menu.setPlugin(getPlugin());
menu.setUuid(getUuid());
menu.open(event.getPlayer());
event.setWillOpenMenu(true);
} catch (InstantiationException | IllegalAccessException e)
{
e.printStackTrace();
}
}
/**
* Gets the ItemStack to be shown to the player.
*
* @param player The player.
* @return The final icon.
*/
public ItemStack getFinalIcon(Player player)
{
return setNameAndLore(getIcon().clone(), getDisplayName(), getLore());
}
/**
* Called when the ItemMenu<T> is clicked.
*
* @param event The {@link com.ehaqui.lib.menu.events.ItemClickEvent}.
*/
public abstract void onItemClick(ItemClickEvent event) throws MenuException;
public void process(String text) throws MenuException
{
}
/**
* Sets the current item;
*
* @param item
*/
public Button<T> setItem(ItemStack item)
{
this.icon = item;
if (item.getType() != Material.AIR)
{
if (item.getItemMeta().hasDisplayName())
this.displayName = item.getItemMeta().getDisplayName();
else
this.displayName = "";
if (item.getItemMeta().hasLore())
this.lore = item.getItemMeta().getLore();
else
this.lore = new ArrayList<>();
}
return this;
}
public void getText(ItemClickEvent event, String text, boolean back, String... lore)
{
getText(event, text, new ItemStack(Material.EMERALD_BLOCK), back, lore);
}
public void getText(ItemClickEvent event, String text, String... lore)
{
getText(event, text, new ItemStack(Material.EMERALD_BLOCK), lore);
}
public void getText(ItemClickEvent event, String text, ItemStack icon, String... lore)
{
getText(event, text, icon, true, lore);
}
public void getText(ItemClickEvent event, String text, ItemStack icon, boolean back, String... lore)
{
new BukkitRunnable()
{
@Override
public void run()
{
AnvilGui gui = new AnvilGui(event.getPlayer(), (AnvilClickEventHandler) event2 ->
{
boolean error = false;
if (event2.getSlot() == AnvilSlot.OUTPUT)
{
try
{
process(event2.getText());
} catch (MenuException ex)
{
send("&c" + ex.getMessage());
error = true;
}
}
if (back || error)
{
new BukkitRunnable()
{
@Override
public void run()
{
Menu menu = event.getMenu();
if (menu.getPlugin() == null)
menu.setPlugin(getPlugin());
menu.setUuid(getUuid());
menu.open(event.getPlayer());
}
}.runTaskLater(getPlugin(), 3);
}
event.setWillClose(true);
}, getPlugin());
gui.setSlot(AnvilSlot.INPUT_LEFT, text, icon, lore);
gui.open();
}
}.runTaskLater(getPlugin(), 3);
event.setWillClose(true);
}
public void send(String message)
{
Message.send(getPlayer(), message);
}
public void send(Message.Type type, String... message)
{
if (message.length > 1)
Message.send(type, getPlayer(), message[0], message[1]);
else
Message.send(type, getPlayer(), message[0]);
}
}
| 10,715 | 0.563042 | 0.561363 | 405 | 25.456791 | 24.941734 | 125 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.488889 | false | false | 9 |
108f692da2a973f950c1eec52a2928dccd1827c9 | 31,928,786,892,863 | 7d6b3208ff0156bad5eacc57bf58ab5b7afdcb1d | /android/onboard/src/se/purplescout/purplemow/onboard/db/entity/Constant.java | ee5fc5efe40def48e5994f0947561e83c4837ded | [] | no_license | greymfm/PurpleMow | https://github.com/greymfm/PurpleMow | 174693a90c5344b4bc17c6feaf19480134cb58c7 | 0b65e9a7b48615f715bdaac044c1f00d1fe4a233 | refs/heads/master | 2021-01-15T08:40:36.388000 | 2013-02-07T19:47:50 | 2013-02-07T19:47:50 | 44,382,167 | 1 | 0 | null | true | 2015-10-16T12:01:31 | 2015-10-16T12:01:31 | 2013-10-28T21:37:45 | 2015-01-12T09:19:26 | 13,128 | 0 | 0 | 0 | null | null | null | package se.purplescout.purplemow.onboard.db.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import se.purplescout.purplemow.onboard.shared.constant.enums.ConstantEnum;
import static se.purplescout.purplemow.onboard.db.entity.Constant_.ID;
import static se.purplescout.purplemow.onboard.db.entity.Constant_.NAME;
import static se.purplescout.purplemow.onboard.db.entity.Constant_.VALUE;
@Entity(name = "constant")
public class Constant {
@Id
@Column(name = ID)
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@Column(name = NAME, nullable = false)
@Enumerated(EnumType.STRING)
ConstantEnum name;
@Column(name = VALUE, nullable = false)
int value;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public ConstantEnum getName() {
return name;
}
public void setName(ConstantEnum name) {
this.name = name;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
| UTF-8 | Java | 1,201 | java | Constant.java | Java | [] | null | [] | package se.purplescout.purplemow.onboard.db.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import se.purplescout.purplemow.onboard.shared.constant.enums.ConstantEnum;
import static se.purplescout.purplemow.onboard.db.entity.Constant_.ID;
import static se.purplescout.purplemow.onboard.db.entity.Constant_.NAME;
import static se.purplescout.purplemow.onboard.db.entity.Constant_.VALUE;
@Entity(name = "constant")
public class Constant {
@Id
@Column(name = ID)
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@Column(name = NAME, nullable = false)
@Enumerated(EnumType.STRING)
ConstantEnum name;
@Column(name = VALUE, nullable = false)
int value;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public ConstantEnum getName() {
return name;
}
public void setName(ConstantEnum name) {
this.name = name;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
| 1,201 | 0.757702 | 0.757702 | 55 | 20.836363 | 20.93693 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.018182 | false | false | 9 |
3a18d1d78941a46ac990a03d3b3b5231a325c347 | 31,928,786,893,588 | c5367160660bb0842d632c44db5afa69f9791c14 | /src/main/java/tw/dworker/StuPerson.java | 19c81ce493f27067fe6fa4b6e0b0feba230562c3 | [] | no_license | muscletaipei/myproject2 | https://github.com/muscletaipei/myproject2 | c2fb78470a201f692918cb3ec29c7ccdf292754f | 06bd6884f14645d678a8842e1b99757bd9993060 | refs/heads/master | 2022-12-17T01:25:37.206000 | 2020-09-27T12:18:21 | 2020-09-27T12:18:21 | 298,724,339 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package tw.dworker;
public class StuPerson {
String id;
String name;
int english;
int mat;
public StuPerson() {
}
public StuPerson(String id, String name, int english, int mat) {
this.id = id;
this.name = name;
this.english = english;
this.mat = mat;
}
}
| UTF-8 | Java | 323 | java | StuPerson.java | Java | [] | null | [] | package tw.dworker;
public class StuPerson {
String id;
String name;
int english;
int mat;
public StuPerson() {
}
public StuPerson(String id, String name, int english, int mat) {
this.id = id;
this.name = name;
this.english = english;
this.mat = mat;
}
}
| 323 | 0.563468 | 0.563468 | 19 | 16 | 15.781402 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.631579 | false | false | 9 |
c922eb21e19e06a28e54a08e59d4d1a0c8b4a915 | 5,265,629,927,591 | aa1a80f0a23b2b09d4bb7223045263a77b656ac5 | /src/main/java/me/badcattitude/harrypotterbot/commands/HelpCommand.java | efcf988454575c8c2c96626ae8a5ddeba26bcc28 | [] | no_license | BadCattitude/HarryPotterBot | https://github.com/BadCattitude/HarryPotterBot | c4b3ca3ea4758b5d9e667a1e8a70f1bd34f3ec6c | 8dbba4e41b2f2f541da717bbfbe31c8d001eac17 | refs/heads/master | 2021-07-25T04:49:47.512000 | 2017-11-05T07:57:49 | 2017-11-05T07:57:49 | 107,907,665 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package me.badcattitude.harrypotterbot.commands;
import net.dv8tion.jda.core.entities.Message;
public class HelpCommand extends Command {
@Override
public void execute(Message message, String[] args) {
String website = "";
message.getChannel().sendMessage("Here is a list of commands: " + website).queue();
}
@Override
public String getName() {
return "help";
}
// no extra aliases, so no need to override getAliases
}
| UTF-8 | Java | 486 | java | HelpCommand.java | Java | [] | null | [] | package me.badcattitude.harrypotterbot.commands;
import net.dv8tion.jda.core.entities.Message;
public class HelpCommand extends Command {
@Override
public void execute(Message message, String[] args) {
String website = "";
message.getChannel().sendMessage("Here is a list of commands: " + website).queue();
}
@Override
public String getName() {
return "help";
}
// no extra aliases, so no need to override getAliases
}
| 486 | 0.656379 | 0.654321 | 21 | 22.142857 | 25.121202 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 9 |
117c34d72a7f83b57b82389976e45ec68ff0f31a | 1,975,684,979,986 | 80d45f600e024834e3c25d16bed81971bcb5ebcf | /DataStructure/src/datastructure/testStack.java | 094df987a9c1d8a095509a6af609df6b4ade6f5d | [] | no_license | hw271/course-georgetown | https://github.com/hw271/course-georgetown | 49b8fcd49ed1bfb2ed4c97a07a9cdf7660914f7d | 6927eb1d2b374fe361147303b6a163aad11335bc | refs/heads/master | 2016-03-28T03:45:16.594000 | 2015-12-28T04:27:21 | 2015-12-28T04:27:21 | 41,926,341 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package datastructure;
import java.util.Scanner;
import java.util.Stack;
public class testStack {
private static boolean compare(int nowLevel, Integer previousLevel, String x, Stack<String> operatorStack){
if(nowLevel>previousLevel){
operatorStack.push(x);
return true;
}
else{
String op=operatorStack.pop();
System.out.print(op+" ");
return false;
}
}
public static void arithmaticOperation(){
Scanner sc = new Scanner(System.in);
String line=sc.nextLine();
String[] obj=line.split("\\s");
Stack<String> operatorStack=new Stack<String>();
int previousLevel=0;
int nowLevel=0;
//( 5 + 3 ) / 2 * 4 - 2 * 2
for(String x:obj){
if(x.matches("\\(")){
nowLevel=4;
boolean prechange=compare(nowLevel, previousLevel, x, operatorStack);
if(prechange) previousLevel=nowLevel;
}
else if(x.matches("[\\*/]")){
nowLevel=3;
boolean prechange=compare(nowLevel, previousLevel, x, operatorStack);
if(prechange) previousLevel=nowLevel;
}
else if(x.matches("[\\+-]")){
nowLevel=2;
boolean prechange=compare(nowLevel, previousLevel, x, operatorStack);
if(prechange) previousLevel=nowLevel;
}
else if(x.matches("\\)")){
nowLevel=1;
boolean prechange=compare(nowLevel, previousLevel, x, operatorStack);
if(prechange) previousLevel=nowLevel;
}
else if(x.matches("\\d+")){
System.out.print(x+" ");
}
}
}
}
| UTF-8 | Java | 1,423 | java | testStack.java | Java | [] | null | [] | package datastructure;
import java.util.Scanner;
import java.util.Stack;
public class testStack {
private static boolean compare(int nowLevel, Integer previousLevel, String x, Stack<String> operatorStack){
if(nowLevel>previousLevel){
operatorStack.push(x);
return true;
}
else{
String op=operatorStack.pop();
System.out.print(op+" ");
return false;
}
}
public static void arithmaticOperation(){
Scanner sc = new Scanner(System.in);
String line=sc.nextLine();
String[] obj=line.split("\\s");
Stack<String> operatorStack=new Stack<String>();
int previousLevel=0;
int nowLevel=0;
//( 5 + 3 ) / 2 * 4 - 2 * 2
for(String x:obj){
if(x.matches("\\(")){
nowLevel=4;
boolean prechange=compare(nowLevel, previousLevel, x, operatorStack);
if(prechange) previousLevel=nowLevel;
}
else if(x.matches("[\\*/]")){
nowLevel=3;
boolean prechange=compare(nowLevel, previousLevel, x, operatorStack);
if(prechange) previousLevel=nowLevel;
}
else if(x.matches("[\\+-]")){
nowLevel=2;
boolean prechange=compare(nowLevel, previousLevel, x, operatorStack);
if(prechange) previousLevel=nowLevel;
}
else if(x.matches("\\)")){
nowLevel=1;
boolean prechange=compare(nowLevel, previousLevel, x, operatorStack);
if(prechange) previousLevel=nowLevel;
}
else if(x.matches("\\d+")){
System.out.print(x+" ");
}
}
}
}
| 1,423 | 0.660576 | 0.652143 | 53 | 25.849056 | 22.706823 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.396226 | false | false | 9 |
f8fd7d8041217e65778630b2f4a75594e83e30a6 | 11,836,929,933,135 | e29cabea2df5bfe1fc4ed83ffc411e5a4fdb9eea | /app/src/main/java/com/mobiledev/fizus/remindme/Model/RoutineModel.java | 0f12579da36d24739ee3337ff8ea848827f97563 | [] | no_license | fikr-mobiledev/RemindMe | https://github.com/fikr-mobiledev/RemindMe | bf776171fb85cc59c77f13449105949d66a181f0 | 1d7fcb4651b065f126ca9674fca9f41c04cefaaa | refs/heads/master | 2020-04-07T11:52:26.156000 | 2018-11-21T20:07:23 | 2018-11-21T20:07:23 | 158,345,011 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.mobiledev.fizus.remindme.Model;
public class RoutineModel {
private int id;
private String routineName;
//private String routineDescription;
private String routineTime;
private String day;
private boolean isRepeat;
public RoutineModel(int id, String routineName, String routineTime, String day, boolean isRepeat) {
this.id = id;
this.routineName = routineName;
//this.routineDescription = routineDescription;
this.day = day;
this.routineTime = routineTime;
this.isRepeat = isRepeat;
}
public int getId() {
return id;
}
public String getRoutineName() {
return routineName;
}
// public String getRoutineDescription() {
// return routineDescription;
// }
public String getDay() {
return day;
}
public String getRoutineTime() {
return routineTime;
}
public boolean isRepeat() {
return isRepeat;
}
}
| UTF-8 | Java | 991 | java | RoutineModel.java | Java | [] | null | [] | package com.mobiledev.fizus.remindme.Model;
public class RoutineModel {
private int id;
private String routineName;
//private String routineDescription;
private String routineTime;
private String day;
private boolean isRepeat;
public RoutineModel(int id, String routineName, String routineTime, String day, boolean isRepeat) {
this.id = id;
this.routineName = routineName;
//this.routineDescription = routineDescription;
this.day = day;
this.routineTime = routineTime;
this.isRepeat = isRepeat;
}
public int getId() {
return id;
}
public String getRoutineName() {
return routineName;
}
// public String getRoutineDescription() {
// return routineDescription;
// }
public String getDay() {
return day;
}
public String getRoutineTime() {
return routineTime;
}
public boolean isRepeat() {
return isRepeat;
}
}
| 991 | 0.632694 | 0.632694 | 42 | 22.595238 | 19.911781 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.547619 | false | false | 9 |
5b51e486abeafc8667d694d674ae76afeb0371df | 17,660,905,560,228 | 130758fde289e045793ac023c8f311e7b7216f47 | /spark-plugins/src/main/java/co/cask/hydrator/plugin/spark/featureExtraction/FeatureSelectorClassifierPlugin.java | 5b7251fe5bea852d0d0012b853b291ad55c93828 | [] | no_license | pergrand/master | https://github.com/pergrand/master | 3a618c18003a7408afb910ef9250197f49770737 | 9c273b5c5a7bc98a4a2fcd2851aa0eb04bbecff1 | refs/heads/master | 2019-07-10T11:01:10.245000 | 2017-05-15T10:49:01 | 2017-05-15T10:49:01 | 91,311,906 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package co.cask.hydrator.plugin.spark.featureExtraction;
import co.cask.cdap.api.annotation.Description;
import co.cask.cdap.api.annotation.Name;
import co.cask.cdap.api.annotation.Plugin;
import co.cask.cdap.etl.api.PipelineConfigurer;
import co.cask.hydrator.plugin.spark.featureExtraction.config.FeatureSelectorClassifierConfig;
import co.cask.hydrator.plugin.spark.util.FeatureMethod;
import co.cask.hydrator.plugin.spark.SchemaUtils;
import co.cask.hydrator.plugin.spark.util.TypeConvertUtils;
import co.cask.hydrator.plugin.spark.util.VectorType;
import org.apache.spark.api.java.JavaRDD;
import co.cask.cdap.api.data.format.StructuredRecord;
import co.cask.cdap.etl.api.batch.SparkCompute;
import co.cask.cdap.etl.api.batch.SparkExecutionPluginContext;
import org.apache.spark.api.java.function.Function;
import org.apache.spark.mllib.linalg.Vector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Plugin(type = SparkCompute.PLUGIN_TYPE)
@Name(FeatureSelectorClassifierPlugin.NAME)
@Description("特征选择学习插件")
public class FeatureSelectorClassifierPlugin extends SparkCompute<StructuredRecord, StructuredRecord> {
public final static String NAME = "FeatureSelectorClassifier";
private static final Logger logger = LoggerFactory.getLogger(FeatureSelectorClassifierPlugin.class);
private FeatureSelectorClassifierConfig config;
private FeatureSelector selector;
public FeatureSelectorClassifierPlugin(FeatureSelectorClassifierConfig config) {
this.config = config;
}
@Override
public JavaRDD<StructuredRecord> transform(
SparkExecutionPluginContext context, JavaRDD<StructuredRecord> input)
throws Exception {
JavaRDD<StructuredRecord> output = input.map(new Function<StructuredRecord, StructuredRecord>() {
@Override
public StructuredRecord call(StructuredRecord structuredRecord) throws Exception {
String text = structuredRecord.get(config.featureField);
Vector vector = TypeConvertUtils.string2Vector(text, config.featureSplit);
Vector predict = selector.transform(vector);
return SchemaUtils.cloneRecord(structuredRecord, config.outputField).set(config.outputField, TypeConvertUtils.vector2String(predict, VectorType.valueOf(config.outputFormat), config.featureSplit)).build();
}
});
return output;
}
private void initSelector(SparkExecutionPluginContext context,
FeatureSelectorClassifierConfig config) {
String method = selector.getFeatureMethod(context, config);
if (method.equals(FeatureMethod.chiSq.toString())) {
selector = new ChiSqFeatureSelector();
} else if (method.equals(FeatureMethod.pca.toString())) {
selector = new PCASelector();
} else if (method.equals(FeatureMethod.svd.toString())) {
selector = new SVDSelector();
} else if (method.equals(FeatureMethod.dspca.toString())) {
selector = new DSPCASelector();
}
selector.loadModel(context, config);
}
@Override
public void configurePipeline(PipelineConfigurer pipelineConfigurer) throws IllegalArgumentException {
super.configurePipeline(pipelineConfigurer);
}
@Override
public void initialize(SparkExecutionPluginContext context) throws Exception {
if (selector == null) {
initSelector(context, this.config);
}
super.initialize(context);
}
}
| UTF-8 | Java | 3,553 | java | FeatureSelectorClassifierPlugin.java | Java | [] | null | [] | package co.cask.hydrator.plugin.spark.featureExtraction;
import co.cask.cdap.api.annotation.Description;
import co.cask.cdap.api.annotation.Name;
import co.cask.cdap.api.annotation.Plugin;
import co.cask.cdap.etl.api.PipelineConfigurer;
import co.cask.hydrator.plugin.spark.featureExtraction.config.FeatureSelectorClassifierConfig;
import co.cask.hydrator.plugin.spark.util.FeatureMethod;
import co.cask.hydrator.plugin.spark.SchemaUtils;
import co.cask.hydrator.plugin.spark.util.TypeConvertUtils;
import co.cask.hydrator.plugin.spark.util.VectorType;
import org.apache.spark.api.java.JavaRDD;
import co.cask.cdap.api.data.format.StructuredRecord;
import co.cask.cdap.etl.api.batch.SparkCompute;
import co.cask.cdap.etl.api.batch.SparkExecutionPluginContext;
import org.apache.spark.api.java.function.Function;
import org.apache.spark.mllib.linalg.Vector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Plugin(type = SparkCompute.PLUGIN_TYPE)
@Name(FeatureSelectorClassifierPlugin.NAME)
@Description("特征选择学习插件")
public class FeatureSelectorClassifierPlugin extends SparkCompute<StructuredRecord, StructuredRecord> {
public final static String NAME = "FeatureSelectorClassifier";
private static final Logger logger = LoggerFactory.getLogger(FeatureSelectorClassifierPlugin.class);
private FeatureSelectorClassifierConfig config;
private FeatureSelector selector;
public FeatureSelectorClassifierPlugin(FeatureSelectorClassifierConfig config) {
this.config = config;
}
@Override
public JavaRDD<StructuredRecord> transform(
SparkExecutionPluginContext context, JavaRDD<StructuredRecord> input)
throws Exception {
JavaRDD<StructuredRecord> output = input.map(new Function<StructuredRecord, StructuredRecord>() {
@Override
public StructuredRecord call(StructuredRecord structuredRecord) throws Exception {
String text = structuredRecord.get(config.featureField);
Vector vector = TypeConvertUtils.string2Vector(text, config.featureSplit);
Vector predict = selector.transform(vector);
return SchemaUtils.cloneRecord(structuredRecord, config.outputField).set(config.outputField, TypeConvertUtils.vector2String(predict, VectorType.valueOf(config.outputFormat), config.featureSplit)).build();
}
});
return output;
}
private void initSelector(SparkExecutionPluginContext context,
FeatureSelectorClassifierConfig config) {
String method = selector.getFeatureMethod(context, config);
if (method.equals(FeatureMethod.chiSq.toString())) {
selector = new ChiSqFeatureSelector();
} else if (method.equals(FeatureMethod.pca.toString())) {
selector = new PCASelector();
} else if (method.equals(FeatureMethod.svd.toString())) {
selector = new SVDSelector();
} else if (method.equals(FeatureMethod.dspca.toString())) {
selector = new DSPCASelector();
}
selector.loadModel(context, config);
}
@Override
public void configurePipeline(PipelineConfigurer pipelineConfigurer) throws IllegalArgumentException {
super.configurePipeline(pipelineConfigurer);
}
@Override
public void initialize(SparkExecutionPluginContext context) throws Exception {
if (selector == null) {
initSelector(context, this.config);
}
super.initialize(context);
}
}
| 3,553 | 0.73339 | 0.732259 | 79 | 43.772152 | 35.648407 | 220 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.632911 | false | false | 9 |
2e34799eaa21973e6005068d6f0d98de45a04f3d | 25,048,249,312,393 | b9b5e9ba72bb76b28b450993f746ab1b5ac76f8f | /EcoRe/src/RecycleMachine.java | a9e28a5f0731c318f15f5befaad50c8fc1e74b48 | [] | no_license | Hiloryw/EcoSystem | https://github.com/Hiloryw/EcoSystem | cb99446380ac7ad7888628a0754b4ccb11e642c7 | 77c5a7cf6b97b9f9fa1a777ff70f018f6eff3a9c | refs/heads/master | 2022-11-27T19:44:03.736000 | 2020-08-06T22:45:30 | 2020-08-06T22:45:30 | 285,681,418 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.*;
public class RecycleMachine extends Machine{
private HashMap<String, Double> priceMap;
private int machineNum;
private String location;
private String id;
private boolean status;
private RecycleMachineView view;
double capacity;
double leftCapacity;
double usedCapacity;
double onceWeight;
double monthlyWeight;
double money;
double leftMoney;
double totalIssuedMoney;
double monthlyMoney;
int itemNum;
int emptyNum;
String emptyTime;
public void setMachineNum(int machineNum){
this.machineNum = machineNum;
}
public int getMachineNum(){
return machineNum;
}
public void setItemNum(int itemNum){
this.itemNum = itemNum;
}
public int getItemNum(){
return itemNum;
}
public void setEmptyNum(int emptyNum){
this.emptyNum = emptyNum;
}
public int getEmptyNum(){
return emptyNum;
}
public void setLocation(String location){
this.location = location;
}
public String getLocation(){
return location;
}
public void setId(String id){
this.id = id;
}
public String getId(){
return id;
}
public void setStatus(boolean status){
this.status = status;
}
public boolean getStatus(){
return status;
}
public void setLeftCapacity(double leftCapacity){
this.leftCapacity = leftCapacity;
}
public double getLeftCapacity(){
return leftCapacity;
}
public void setUsedCapacity(double usedCapacity){
this.usedCapacity = usedCapacity;
}
public double getUsedCapacity(){
return usedCapacity;
}
public void setOnceWeight(double onceWeight){
this.onceWeight = onceWeight;
}
public double getOnceWeight(){
return onceWeight;
}
public void setMonthlyWeight(double monthlyWeight){
this.monthlyWeight = monthlyWeight;
}
public double getMonthlyWeight(){
return monthlyWeight;
}
public void setLeftMoney(double leftMoney){
this.leftMoney = leftMoney;
}
public double getLeftMoney(){
return leftMoney;
}
public void setMonthlyMoney(double monthlyMoney){
this.monthlyMoney = monthlyMoney;
}
public double getMonthlyMoney(){
return monthlyMoney;
}
public void setTotalMoney(double totalIssuedMoney){
this.totalIssuedMoney = totalIssuedMoney;
}
public double getTotalMoney(){
return totalIssuedMoney;
}
public void setPriceMap(HashMap<String, Double> priceMap) {
this.priceMap = priceMap;
}
public HashMap<String, Double> getPriceMap() {
return priceMap;
}
public void setEmptyTime(String emptyTime) {
this.emptyTime = emptyTime;
}
public String getEmptyTime() {
return emptyTime;
}
public void setView(RecycleMachineView view) {
this.view = view;
}
public RecycleMachineView getView() {
return view;
}
@Override
public RecycleMachine getMachine(HashMap<String, Double> priceMap, String location, String id, boolean status, double money, double capacity) {
this.priceMap = priceMap;
this.location = location;
this.id = id;
this.status = status;
this.money = money;
this.capacity = capacity;
leftMoney = money;
leftCapacity = capacity;
usedCapacity = capacity - leftCapacity;
monthlyWeight += usedCapacity;
totalIssuedMoney = 0.0;
monthlyMoney += totalIssuedMoney;
return this;
}
}
| UTF-8 | Java | 3,207 | java | RecycleMachine.java | Java | [] | null | [] | import java.util.*;
public class RecycleMachine extends Machine{
private HashMap<String, Double> priceMap;
private int machineNum;
private String location;
private String id;
private boolean status;
private RecycleMachineView view;
double capacity;
double leftCapacity;
double usedCapacity;
double onceWeight;
double monthlyWeight;
double money;
double leftMoney;
double totalIssuedMoney;
double monthlyMoney;
int itemNum;
int emptyNum;
String emptyTime;
public void setMachineNum(int machineNum){
this.machineNum = machineNum;
}
public int getMachineNum(){
return machineNum;
}
public void setItemNum(int itemNum){
this.itemNum = itemNum;
}
public int getItemNum(){
return itemNum;
}
public void setEmptyNum(int emptyNum){
this.emptyNum = emptyNum;
}
public int getEmptyNum(){
return emptyNum;
}
public void setLocation(String location){
this.location = location;
}
public String getLocation(){
return location;
}
public void setId(String id){
this.id = id;
}
public String getId(){
return id;
}
public void setStatus(boolean status){
this.status = status;
}
public boolean getStatus(){
return status;
}
public void setLeftCapacity(double leftCapacity){
this.leftCapacity = leftCapacity;
}
public double getLeftCapacity(){
return leftCapacity;
}
public void setUsedCapacity(double usedCapacity){
this.usedCapacity = usedCapacity;
}
public double getUsedCapacity(){
return usedCapacity;
}
public void setOnceWeight(double onceWeight){
this.onceWeight = onceWeight;
}
public double getOnceWeight(){
return onceWeight;
}
public void setMonthlyWeight(double monthlyWeight){
this.monthlyWeight = monthlyWeight;
}
public double getMonthlyWeight(){
return monthlyWeight;
}
public void setLeftMoney(double leftMoney){
this.leftMoney = leftMoney;
}
public double getLeftMoney(){
return leftMoney;
}
public void setMonthlyMoney(double monthlyMoney){
this.monthlyMoney = monthlyMoney;
}
public double getMonthlyMoney(){
return monthlyMoney;
}
public void setTotalMoney(double totalIssuedMoney){
this.totalIssuedMoney = totalIssuedMoney;
}
public double getTotalMoney(){
return totalIssuedMoney;
}
public void setPriceMap(HashMap<String, Double> priceMap) {
this.priceMap = priceMap;
}
public HashMap<String, Double> getPriceMap() {
return priceMap;
}
public void setEmptyTime(String emptyTime) {
this.emptyTime = emptyTime;
}
public String getEmptyTime() {
return emptyTime;
}
public void setView(RecycleMachineView view) {
this.view = view;
}
public RecycleMachineView getView() {
return view;
}
@Override
public RecycleMachine getMachine(HashMap<String, Double> priceMap, String location, String id, boolean status, double money, double capacity) {
this.priceMap = priceMap;
this.location = location;
this.id = id;
this.status = status;
this.money = money;
this.capacity = capacity;
leftMoney = money;
leftCapacity = capacity;
usedCapacity = capacity - leftCapacity;
monthlyWeight += usedCapacity;
totalIssuedMoney = 0.0;
monthlyMoney += totalIssuedMoney;
return this;
}
}
| 3,207 | 0.733084 | 0.73246 | 173 | 17.520231 | 18.525593 | 145 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.554913 | false | false | 9 |
10da5798a383095e9586dfb8325bdbac675d1825 | 21,500,606,295,399 | b707913032c94dbc5c333ccb82a5fb7d54559b07 | /M03B/EAC8/DA2EAC8GestioReservesEnunciat/src/elementsMobils/Cambrer.java | 7b47c4250de6733129eeddfa41e67f5b9e9491fb | [] | no_license | carlosclatg/Java-Institut-Obert | https://github.com/carlosclatg/Java-Institut-Obert | 152a8e27a4b9e9f080cd1026dc30c28126cdc314 | 85bc382953fdee6eb6279ef4a6f5558b1f5b3e14 | refs/heads/master | 2022-12-23T11:13:05.547000 | 2021-07-13T14:30:36 | 2021-07-13T14:30:36 | 178,057,663 | 0 | 0 | null | false | 2022-12-16T00:39:50 | 2019-03-27T19:02:40 | 2021-07-13T14:30:59 | 2022-12-16T00:39:47 | 57,036 | 1 | 0 | 11 | Java | false | false | package elementsMobils;
import java.util.Scanner;
/*
* Classe que defineix un cambrer. Un cambrer es defineix pel seu codi, nom, telefon, torn
* en què treballa (matí, tarda, matí i tarda,etc.) i si està actiu o no.
*/
/**
*
* @author fta
*/
public class Cambrer extends ElementTaula {
private String torn;
private boolean actiu;
/*
TODO CONSTRUCTOR
Paràmetres: valors per tots els atributs de la classe, menys l'atribut actiu,
ja que un cambrer sempre estarà en actiu en el moment que es crea.
Accions:
- Assignar als atributs els valors passats com a paràmetres
- Assignar el valor que sigui escaient a l'atribut actiu
*/
/*
TODO Mètodes accessors
*/
public Cambrer(String codi, String nom, String telefon, String torn) {
super(codi, nom, telefon);
this.torn = torn;
this.actiu = true;
}
public String getTorn() {
return torn;
}
public void setTorn(String pTorn) {
torn = pTorn;
}
public boolean getActiu() {
return actiu;
}
public void setActiu(boolean pActiu) {
actiu = pActiu;
}
/*
TODO
Paràmetres: cap
Accions:
- Demanar a l'usuari les dades per consola per crear un nou cambrer. Les dades
a demanar són les que necessita el constructor.
- També heu de tenir en compte que tant el nom com el torn, poden ser frases,
per exemple, Francesc Xavier, o bé, matí i tarda.
Retorn: El nou cambrer creat.
*/
public static Cambrer addCambrer() {
Scanner dades = new Scanner(System.in);
String codiCambrer;
String nomCambrer;
String telefonCambrer;
String tornCambrer;
System.out.println("Codi del cambrer:");
codiCambrer = dades.next();
dades.nextLine(); //Neteja buffer
System.out.println("Nom del cambrer:");
nomCambrer = dades.nextLine();
System.out.println("Telefon del cambrer:");
telefonCambrer = dades.next();
dades.nextLine(); //Neteja buffer
System.out.println("Torn del cambrer:");
tornCambrer = dades.nextLine();
return new Cambrer(codiCambrer, nomCambrer, telefonCambrer, tornCambrer);
}
/*
Paràmetres: cap
Accions:
- Demanar a l'usuari que introdueixi les noves dades de l'objecte actual
i modificar els atributs corresponents d'aquest objecte.
-Quan mostreu a l'usuari si està actiu o no, ho heu de fer mostrant-li els missatges
"actiu" o "no actiu".
-Quan es demani que s'introdueixi el nou estat (si està actiu o no) del cambrer,
se li ha d'indicar a l'usuari que introdueixi "1" o "0". Si introdueix 1,
el cambrer estarà en actiu i si introdueix 0, doncs no ho estarà. Si l'usuari
no introdueix un valor correcte, l'heu d'avisar i tornar a demanar que introdueixi
l'estat del cambrer, així fins que introdueixi el valor correcte.
- Li heu de mostrar a l'usuari el valor actual dels atributs de l'objecte
actual, abans de modificar-los
Retorn: cap
*/
public void updateCambrer() {
Scanner dades = new Scanner(System.in);
boolean valorCorrecte = false;
String estatCambrer;
// Es podria fer els tres primers atributs(els heretats de ElementTaula) també amb super.updateElement(), aplicacant herència.
//Ho deixo així per a que quedi més clar que és una cambrer.
System.out.println("\nCodi del cambrer: " + super.getCodi());
System.out.println("\nEntra el nou codi:");
super.setCodi(dades.next());
dades.nextLine(); //Neteja buffer
System.out.println("\nNom del cambrer: " + super.getNom());
System.out.println("\nEntra el nou nom:");
super.setNom(dades.nextLine());
System.out.println("\nTelefon del cambrer: " + super.getTelefon());
System.out.println("\nEntra el nou telefon:");
super.setTelefon(dades.next());
System.out.println("\nTorn del cambrer: " + torn);
System.out.println("\nEntra el nou torn:");
torn = dades.nextLine();
System.out.print("\nEstat del cambrer: ");
if (actiu) {
System.out.println("actiu");
} else {
System.out.println("no actiu");
}
while (!valorCorrecte) {
System.out.println("\nEntra el nou estat(Escriu 1 o 0):");
estatCambrer = dades.next();
if (estatCambrer.equals("1")) {
actiu = true;
valorCorrecte = true;
} else if (estatCambrer.equals("0")) {
actiu = false;
valorCorrecte = true;
}
}
}
public void showCambrer() {
// Es podria fer els tres primers atributs (els heretats de ElementTaula) també amb super.updateElement(), aplicacant herència.
//Ho deixo així per a que quedi més clar que és una cambrer.
System.out.println("\nLes dades del cambrer amb codi " + super.getCodi() + " són:");
System.out.println("\nNom:" + super.getNom());
System.out.println("\nTelefon:" + super.getTelefon());
System.out.println("\nTorn:" + torn);
System.out.print("\nEstat: ");
if (actiu) {
System.out.println("actiu");
} else {
System.out.println("no actiu");
}
}
}
| UTF-8 | Java | 5,451 | java | Cambrer.java | Java | [
{
"context": ",etc.) i si està actiu o no.\n */\n/**\n *\n * @author fta\n */\npublic class Cambrer extends ElementTaula {\n\n",
"end": 247,
"score": 0.9995976686477661,
"start": 244,
"tag": "USERNAME",
"value": "fta"
},
{
"context": "m com el torn, poden ser frases,\n per exemple, Francesc Xavier, o bé, matí i tarda.\n Retorn: El nou cambrer ",
"end": 1472,
"score": 0.9998193979263306,
"start": 1457,
"tag": "NAME",
"value": "Francesc Xavier"
}
] | null | [] | package elementsMobils;
import java.util.Scanner;
/*
* Classe que defineix un cambrer. Un cambrer es defineix pel seu codi, nom, telefon, torn
* en què treballa (matí, tarda, matí i tarda,etc.) i si està actiu o no.
*/
/**
*
* @author fta
*/
public class Cambrer extends ElementTaula {
private String torn;
private boolean actiu;
/*
TODO CONSTRUCTOR
Paràmetres: valors per tots els atributs de la classe, menys l'atribut actiu,
ja que un cambrer sempre estarà en actiu en el moment que es crea.
Accions:
- Assignar als atributs els valors passats com a paràmetres
- Assignar el valor que sigui escaient a l'atribut actiu
*/
/*
TODO Mètodes accessors
*/
public Cambrer(String codi, String nom, String telefon, String torn) {
super(codi, nom, telefon);
this.torn = torn;
this.actiu = true;
}
public String getTorn() {
return torn;
}
public void setTorn(String pTorn) {
torn = pTorn;
}
public boolean getActiu() {
return actiu;
}
public void setActiu(boolean pActiu) {
actiu = pActiu;
}
/*
TODO
Paràmetres: cap
Accions:
- Demanar a l'usuari les dades per consola per crear un nou cambrer. Les dades
a demanar són les que necessita el constructor.
- També heu de tenir en compte que tant el nom com el torn, poden ser frases,
per exemple, <NAME>, o bé, matí i tarda.
Retorn: El nou cambrer creat.
*/
public static Cambrer addCambrer() {
Scanner dades = new Scanner(System.in);
String codiCambrer;
String nomCambrer;
String telefonCambrer;
String tornCambrer;
System.out.println("Codi del cambrer:");
codiCambrer = dades.next();
dades.nextLine(); //Neteja buffer
System.out.println("Nom del cambrer:");
nomCambrer = dades.nextLine();
System.out.println("Telefon del cambrer:");
telefonCambrer = dades.next();
dades.nextLine(); //Neteja buffer
System.out.println("Torn del cambrer:");
tornCambrer = dades.nextLine();
return new Cambrer(codiCambrer, nomCambrer, telefonCambrer, tornCambrer);
}
/*
Paràmetres: cap
Accions:
- Demanar a l'usuari que introdueixi les noves dades de l'objecte actual
i modificar els atributs corresponents d'aquest objecte.
-Quan mostreu a l'usuari si està actiu o no, ho heu de fer mostrant-li els missatges
"actiu" o "no actiu".
-Quan es demani que s'introdueixi el nou estat (si està actiu o no) del cambrer,
se li ha d'indicar a l'usuari que introdueixi "1" o "0". Si introdueix 1,
el cambrer estarà en actiu i si introdueix 0, doncs no ho estarà. Si l'usuari
no introdueix un valor correcte, l'heu d'avisar i tornar a demanar que introdueixi
l'estat del cambrer, així fins que introdueixi el valor correcte.
- Li heu de mostrar a l'usuari el valor actual dels atributs de l'objecte
actual, abans de modificar-los
Retorn: cap
*/
public void updateCambrer() {
Scanner dades = new Scanner(System.in);
boolean valorCorrecte = false;
String estatCambrer;
// Es podria fer els tres primers atributs(els heretats de ElementTaula) també amb super.updateElement(), aplicacant herència.
//Ho deixo així per a que quedi més clar que és una cambrer.
System.out.println("\nCodi del cambrer: " + super.getCodi());
System.out.println("\nEntra el nou codi:");
super.setCodi(dades.next());
dades.nextLine(); //Neteja buffer
System.out.println("\nNom del cambrer: " + super.getNom());
System.out.println("\nEntra el nou nom:");
super.setNom(dades.nextLine());
System.out.println("\nTelefon del cambrer: " + super.getTelefon());
System.out.println("\nEntra el nou telefon:");
super.setTelefon(dades.next());
System.out.println("\nTorn del cambrer: " + torn);
System.out.println("\nEntra el nou torn:");
torn = dades.nextLine();
System.out.print("\nEstat del cambrer: ");
if (actiu) {
System.out.println("actiu");
} else {
System.out.println("no actiu");
}
while (!valorCorrecte) {
System.out.println("\nEntra el nou estat(Escriu 1 o 0):");
estatCambrer = dades.next();
if (estatCambrer.equals("1")) {
actiu = true;
valorCorrecte = true;
} else if (estatCambrer.equals("0")) {
actiu = false;
valorCorrecte = true;
}
}
}
public void showCambrer() {
// Es podria fer els tres primers atributs (els heretats de ElementTaula) també amb super.updateElement(), aplicacant herència.
//Ho deixo així per a que quedi més clar que és una cambrer.
System.out.println("\nLes dades del cambrer amb codi " + super.getCodi() + " són:");
System.out.println("\nNom:" + super.getNom());
System.out.println("\nTelefon:" + super.getTelefon());
System.out.println("\nTorn:" + torn);
System.out.print("\nEstat: ");
if (actiu) {
System.out.println("actiu");
} else {
System.out.println("no actiu");
}
}
}
| 5,442 | 0.612802 | 0.611326 | 155 | 33.974194 | 28.054314 | 135 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.574194 | false | false | 9 |
246b7f73fdf169a7a8a21eafc629c2d98e88e59a | 35,072,702,955,938 | 92da484483ec317b8688e94d67fcfbe4f65eacce | /src/com/example/basictwitter/fragments/ScrollingTimeline.java | b093fd199806f8309ac5537c06024a3a74168f37 | [] | no_license | cloudbank/twitterclient | https://github.com/cloudbank/twitterclient | 2ebc0419f6cc8ed16b92a6d10209d2ce0a922758 | 1430ccc2bd091e3182cfc101628f57fdf391c044 | refs/heads/master | 2021-01-20T09:01:43.906000 | 2015-01-15T08:43:59 | 2015-01-15T08:43:59 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.basictwitter.fragments;
import com.loopj.android.http.RequestParams;
public interface ScrollingTimeline {
//cannot make the base class abstract
void populateTimeline(RequestParams p, boolean b);
void customLoadMoreDataFromApi(int p);
}
| UTF-8 | Java | 278 | java | ScrollingTimeline.java | Java | [] | null | [] | package com.example.basictwitter.fragments;
import com.loopj.android.http.RequestParams;
public interface ScrollingTimeline {
//cannot make the base class abstract
void populateTimeline(RequestParams p, boolean b);
void customLoadMoreDataFromApi(int p);
}
| 278 | 0.766187 | 0.766187 | 15 | 17.533333 | 20.985287 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 9 |
bdfbc91c265ba6b585d416fa0013d0888c36fc40 | 33,346,126,131,842 | 15e64651ac237694a9690eccd2e58690625ca099 | /src/main/java/duke/tasks/ToDo.java | 5be325b0e49948a92729140134955b54ca536558 | [
"MIT"
] | permissive | HashirZahir/DukeTeam | https://github.com/HashirZahir/DukeTeam | a770cb3adfc588b6f128617643f7a74d34f4d437 | abf89ce5372d68cd76c619fe8225030077f304ab | refs/heads/master | 2020-07-27T11:50:25.832000 | 2019-09-27T04:05:21 | 2019-09-27T04:05:21 | 209,080,483 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package duke.tasks;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* Task is a public class that extends from Task.
*/
public class ToDo extends Task {
protected int duration;
/**
* Primary constructor of ToDo object.
* @param description the description of the todo object
*/
public ToDo(String description) {
super(description);
super.type = "T";
this.datetime = null;
this.end = null;
}
/**
* Secondary constructor of ToDo object with period.
* @param description description embedded in object
* @param inputStart start of period of task
* @param inputEnd end of period of task
*/
public ToDo(String description, String inputStart, String inputEnd) {
super(description);
SimpleDateFormat dateparser = new SimpleDateFormat("dd/MM/yyyy HHmm");
Date date;
try {
date = dateparser.parse(inputStart);
this.datetime.setTime(date);
date = dateparser.parse(inputEnd);
this.end.setTime(date);
} catch (ParseException e) {
SimpleDateFormat altparser = new SimpleDateFormat("dd MMMM yyyy hh.mm a");
try {
date = altparser.parse(inputStart);
this.datetime.setTime(date);
date = altparser.parse(inputEnd);
this.end.setTime(date);
} catch (ParseException f) {
this.datetime = null;
this.end = null;
}
}
if (this.datetime.after(this.end)) {
Calendar temp = this.datetime;
this.datetime = this.end;
this.end = temp;
}
super.type = "T";
subtypes += "P";
}
/**
* Tertiary constructor of ToDo object with fixedDuration.
* @param description description embedded in object
* @param duration duration of task
*/
public ToDo(String description, String duration) {
super(description);
this.duration = Integer.parseInt(duration);
super.type = "T";
subtypes += "F";
this.datetime = null;
this.end = null;
}
/**
* this function overrides the toString() function in Task to represents the full description of a ToDo object.
* @return <code>"[T]" + super.toString()</code>
* <code>"[T]" + super.toString() + "(From: " + dateFormat.format(datetime.getTime())
* + " to " + dateFormat.format(datetime2.getTime()) + ")"</code>
*/
@Override
public String toString() {
String text = "";
if (subtypes.trim().isEmpty()) {
text += "[T]" + super.toString() + "";
} else if (subtypes.contains("P")) {
DateFormat dateFormat = new SimpleDateFormat("dd MMMM yyyy hh.mm a");
text += "[T]" + super.toString() + "(From: " + dateFormat.format(this.datetime.getTime())
+ " to " + dateFormat.format(this.end.getTime()) + ")";
} else if (subtypes.contains("F")) {
text += "[T]" + super.toString() + " (needs: " + this.duration + ")";
}
for (int i = 0; i < this.doAfter.size(); i += 1) {
text += "\n";
text += this.doAfter.get(i).toString();
}
return text;
}
}
| UTF-8 | Java | 3,436 | java | ToDo.java | Java | [] | null | [] | package duke.tasks;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* Task is a public class that extends from Task.
*/
public class ToDo extends Task {
protected int duration;
/**
* Primary constructor of ToDo object.
* @param description the description of the todo object
*/
public ToDo(String description) {
super(description);
super.type = "T";
this.datetime = null;
this.end = null;
}
/**
* Secondary constructor of ToDo object with period.
* @param description description embedded in object
* @param inputStart start of period of task
* @param inputEnd end of period of task
*/
public ToDo(String description, String inputStart, String inputEnd) {
super(description);
SimpleDateFormat dateparser = new SimpleDateFormat("dd/MM/yyyy HHmm");
Date date;
try {
date = dateparser.parse(inputStart);
this.datetime.setTime(date);
date = dateparser.parse(inputEnd);
this.end.setTime(date);
} catch (ParseException e) {
SimpleDateFormat altparser = new SimpleDateFormat("dd MMMM yyyy hh.mm a");
try {
date = altparser.parse(inputStart);
this.datetime.setTime(date);
date = altparser.parse(inputEnd);
this.end.setTime(date);
} catch (ParseException f) {
this.datetime = null;
this.end = null;
}
}
if (this.datetime.after(this.end)) {
Calendar temp = this.datetime;
this.datetime = this.end;
this.end = temp;
}
super.type = "T";
subtypes += "P";
}
/**
* Tertiary constructor of ToDo object with fixedDuration.
* @param description description embedded in object
* @param duration duration of task
*/
public ToDo(String description, String duration) {
super(description);
this.duration = Integer.parseInt(duration);
super.type = "T";
subtypes += "F";
this.datetime = null;
this.end = null;
}
/**
* this function overrides the toString() function in Task to represents the full description of a ToDo object.
* @return <code>"[T]" + super.toString()</code>
* <code>"[T]" + super.toString() + "(From: " + dateFormat.format(datetime.getTime())
* + " to " + dateFormat.format(datetime2.getTime()) + ")"</code>
*/
@Override
public String toString() {
String text = "";
if (subtypes.trim().isEmpty()) {
text += "[T]" + super.toString() + "";
} else if (subtypes.contains("P")) {
DateFormat dateFormat = new SimpleDateFormat("dd MMMM yyyy hh.mm a");
text += "[T]" + super.toString() + "(From: " + dateFormat.format(this.datetime.getTime())
+ " to " + dateFormat.format(this.end.getTime()) + ")";
} else if (subtypes.contains("F")) {
text += "[T]" + super.toString() + " (needs: " + this.duration + ")";
}
for (int i = 0; i < this.doAfter.size(); i += 1) {
text += "\n";
text += this.doAfter.get(i).toString();
}
return text;
}
}
| 3,436 | 0.558498 | 0.557625 | 101 | 33.019802 | 25.035412 | 115 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.485149 | false | false | 9 |
a2d984ec2e971ff17bb57d61fc9c6b25856afa9e | 970,662,636,236 | d94ee5df1c2f2a49032015bccbfebadced83241f | /app/src/main/java/com/sih/resthousefe/Extend.java | b48912403364851c8f7f65c8ba50814056b93c37 | [] | no_license | VenkatKumari/RestHouseFE | https://github.com/VenkatKumari/RestHouseFE | c23d66a7d56dd5d3cd66339a9ab73dd430cdc7ea | ad375ae956e5e175c34df4a3bc2ec7dc03336d0c | refs/heads/master | 2020-06-05T15:18:20.853000 | 2019-06-18T06:09:37 | 2019-06-18T06:09:37 | 192,470,720 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.sih.resthousefe;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import butterknife.BindView;
import butterknife.ButterKnife;
public class Extend extends AppCompatActivity {
@BindView(R.id.confirm)
Button Confirm;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.extend);
ButterKnife.bind(this);
Confirm.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(Extend.this,Booked_Rooms.class);
startActivity(intent);
}
});
}
}
| UTF-8 | Java | 878 | java | Extend.java | Java | [] | null | [] | package com.sih.resthousefe;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import butterknife.BindView;
import butterknife.ButterKnife;
public class Extend extends AppCompatActivity {
@BindView(R.id.confirm)
Button Confirm;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.extend);
ButterKnife.bind(this);
Confirm.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(Extend.this,Booked_Rooms.class);
startActivity(intent);
}
});
}
}
| 878 | 0.690205 | 0.689066 | 34 | 24.82353 | 20.783861 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 9 |
1505b94f68f407425886b5aa42ffe15f2fce7a34 | 36,172,214,575,608 | 3f207614a2b688a4f3aec44c34aefdff333efc74 | /web/src/main/java/com/ireland/travel/web/service/AuthService.java | 48ace33b2b90def6c22bbb444137b313a7b5e50f | [] | no_license | RobbyWD/ireland | https://github.com/RobbyWD/ireland | 185d1d46e3f30cafbd22d73cc007cff643c76f6f | 7afdc8fe6c9376c0c11f30a74b2c27b0ce5a7732 | refs/heads/master | 2021-01-23T10:44:35.441000 | 2016-02-21T21:32:25 | 2016-02-21T21:32:25 | 39,404,388 | 0 | 1 | null | false | 2015-10-21T11:50:27 | 2015-07-20T19:33:37 | 2015-07-20T19:41:37 | 2015-10-21T11:50:27 | 3,468 | 0 | 1 | 7 | Java | null | null | package com.ireland.travel.web.service;
import java.util.List;
import com.ireland.travel.entity.domain.Authority;
import com.ireland.travel.web.repository.AuthorityRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import com.google.common.collect.Lists;
@Service
public class AuthService {
@Autowired
private AuthorityRepository authRepository;
public long countAllUsers() {
return authRepository.count();
}
public void deleteUser(Authority user) {
authRepository.delete(user);
}
public Authority findUser(Long id) {
return authRepository.findOne(id);
}
public Authority findUser(String name) {
return authRepository.findByUsernameEquals(name);
}
public List<Authority> findAllUsers() {
return Lists.newArrayList(authRepository.findAll());
}
public List<Authority> findUserEntries(int firstResult, int maxResults) {
final PageRequest pageRequest = new PageRequest(firstResult, maxResults);
return Lists.newArrayList(authRepository.findAll(pageRequest));
}
public void saveUser(Authority user) {
authRepository.save(user);
}
public Authority updateUser(Authority user) {
return authRepository.save(user);
}
public void delete(Long id) {
authRepository.delete(id);
}
}
| UTF-8 | Java | 1,419 | java | AuthService.java | Java | [] | null | [] | package com.ireland.travel.web.service;
import java.util.List;
import com.ireland.travel.entity.domain.Authority;
import com.ireland.travel.web.repository.AuthorityRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import com.google.common.collect.Lists;
@Service
public class AuthService {
@Autowired
private AuthorityRepository authRepository;
public long countAllUsers() {
return authRepository.count();
}
public void deleteUser(Authority user) {
authRepository.delete(user);
}
public Authority findUser(Long id) {
return authRepository.findOne(id);
}
public Authority findUser(String name) {
return authRepository.findByUsernameEquals(name);
}
public List<Authority> findAllUsers() {
return Lists.newArrayList(authRepository.findAll());
}
public List<Authority> findUserEntries(int firstResult, int maxResults) {
final PageRequest pageRequest = new PageRequest(firstResult, maxResults);
return Lists.newArrayList(authRepository.findAll(pageRequest));
}
public void saveUser(Authority user) {
authRepository.save(user);
}
public Authority updateUser(Authority user) {
return authRepository.save(user);
}
public void delete(Long id) {
authRepository.delete(id);
}
}
| 1,419 | 0.744186 | 0.744186 | 58 | 23.465517 | 23.666662 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.758621 | false | false | 9 |
d0fdddcf10ca2315c96021bf7d127b9e329342db | 37,761,352,470,090 | 7cab57150b6a5bc2bb75c09fc3c0cf2f5cae043a | /Striver's SDE Sheet/Day 18/zigzagLevelOrder.java | 4ecf52c71d7d86af29fc03d3fed83b266a5481ad | [] | no_license | Machine-Learning-Moron/DataStructures-Python | https://github.com/Machine-Learning-Moron/DataStructures-Python | 0a0a86f5492f7a12ef41ecc51babb3ec30ceba7e | 0079cee958de08aa3f5e52df875c77d47001ed3d | refs/heads/main | 2023-05-10T22:13:01.357000 | 2022-12-03T13:07:19 | 2022-12-03T13:07:19 | 361,775,414 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
Given the root of a binary tree, return the zigzag level order traversal of its nodes' values.
(i.e., from left to right, then right to left for the next level and alternate between).
Constraints:
The number of nodes in the tree is in the range [0, 2000].
-100 <= Node.val <= 100
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
//init result
List<List<Integer>> res = new LinkedList<>();
//base case check
if(root == null)
return res;
//declare queue
Queue<TreeNode> q = new LinkedList<TreeNode>();
//push root to queue before starting anything
q.add(root);
//set a boolean flag
//default value of flag will be false -> which indicate left->right
//otherwise nodes will be pushed in right -> left fashion
boolean leftToRight = false;
//traverse thro the entire size of the queue
while(!q.isEmpty()){
int sizeq = q.size();
LinkedList<Integer> subList = new LinkedList<>();
//loop that traverses thro each node of binary tree
//checks if flag is false -> appends nodes in L->R fashion. otherwise R->L
for(int i = 0; i < sizeq; i++){
//take it out
TreeNode node = q.poll();
//check left subtree or right subtree and push it to queue
if(node.left != null)
q.add(node.left);
if(node.right != null)
q.add(node.right);
//if flag false insert it to subList from the front(L->R) -> addFirst
//otherwise insert it to subList from the back (R->L) -> addLast
//insert
if(leftToRight)
subList.addFirst(node.val);
else
subList.addLast(node.val);
}
//after for loop is executed for a particular level
//reset flag to true
//append subList to res
leftToRight = !leftToRight;
res.add(subList);
}
return res;
}
}
| UTF-8 | Java | 2,661 | java | zigzagLevelOrder.java | Java | [] | null | [] | /*
Given the root of a binary tree, return the zigzag level order traversal of its nodes' values.
(i.e., from left to right, then right to left for the next level and alternate between).
Constraints:
The number of nodes in the tree is in the range [0, 2000].
-100 <= Node.val <= 100
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
//init result
List<List<Integer>> res = new LinkedList<>();
//base case check
if(root == null)
return res;
//declare queue
Queue<TreeNode> q = new LinkedList<TreeNode>();
//push root to queue before starting anything
q.add(root);
//set a boolean flag
//default value of flag will be false -> which indicate left->right
//otherwise nodes will be pushed in right -> left fashion
boolean leftToRight = false;
//traverse thro the entire size of the queue
while(!q.isEmpty()){
int sizeq = q.size();
LinkedList<Integer> subList = new LinkedList<>();
//loop that traverses thro each node of binary tree
//checks if flag is false -> appends nodes in L->R fashion. otherwise R->L
for(int i = 0; i < sizeq; i++){
//take it out
TreeNode node = q.poll();
//check left subtree or right subtree and push it to queue
if(node.left != null)
q.add(node.left);
if(node.right != null)
q.add(node.right);
//if flag false insert it to subList from the front(L->R) -> addFirst
//otherwise insert it to subList from the back (R->L) -> addLast
//insert
if(leftToRight)
subList.addFirst(node.val);
else
subList.addLast(node.val);
}
//after for loop is executed for a particular level
//reset flag to true
//append subList to res
leftToRight = !leftToRight;
res.add(subList);
}
return res;
}
}
| 2,661 | 0.512965 | 0.508455 | 83 | 31.060242 | 23.54199 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.361446 | false | false | 9 |
6dce25587bcf44b43704e58fca40fac0d7c7bb30 | 32,384,053,450,905 | 2d2fa9480e533c56a7af266e0ac1e914089e5d04 | /src/oftp/automaton/network/YesNoNetworkField.java | 1b8a76f022e367ec2b98e9eda871d70b22f61234 | [] | no_license | prShadoko/IGP_OFTP | https://github.com/prShadoko/IGP_OFTP | e214f2bf4b49837f0a9f9164680e3740ed0fdfef | 6abbd54e52d47de1415ad677b099fa4e20d969c3 | refs/heads/master | 2020-04-06T06:50:39.534000 | 2014-05-22T18:54:37 | 2014-05-22T18:54:37 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package oftp.automaton.network;
import automaton.event.network.NetworkField;
import oftp.automaton.YesNo;
public class YesNoNetworkField extends NetworkField<YesNo> {
public YesNoNetworkField(String name, YesNo expectedValue) {
super(name, 1, expectedValue);
}
public YesNoNetworkField(String name) {
super(name, 1);
}
@Override
public YesNo fromString(String str) {
return YesNo.fromChar(str.charAt(0));
}
@Override
public YesNo fromByte(byte[] bytes) {
StringBuilder builder = new StringBuilder();
builder.append(bytes);
return fromString(builder.toString());
}
}
| UTF-8 | Java | 594 | java | YesNoNetworkField.java | Java | [] | null | [] | package oftp.automaton.network;
import automaton.event.network.NetworkField;
import oftp.automaton.YesNo;
public class YesNoNetworkField extends NetworkField<YesNo> {
public YesNoNetworkField(String name, YesNo expectedValue) {
super(name, 1, expectedValue);
}
public YesNoNetworkField(String name) {
super(name, 1);
}
@Override
public YesNo fromString(String str) {
return YesNo.fromChar(str.charAt(0));
}
@Override
public YesNo fromByte(byte[] bytes) {
StringBuilder builder = new StringBuilder();
builder.append(bytes);
return fromString(builder.toString());
}
}
| 594 | 0.752525 | 0.747475 | 27 | 21 | 20.116329 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.296296 | false | false | 9 |
2cb6868d28a568e2d5d8781df002b6fc8ce86ff4 | 32,384,053,449,699 | 2af80de88d98275630f867131ef0ed8c27a8dee7 | /TeamCode/src/main/java/org/firstinspires/ftc/teamcode/util/JsonReaders/NavigationOptionsReader.java | 6191126a55445f201880996a24be2e6cafc82081 | [
"BSD-3-Clause"
] | permissive | ftc-9773/ftc_9773_vv_v2_35 | https://github.com/ftc-9773/ftc_9773_vv_v2_35 | a9a43d5b4470d34c0f6df4dbfa847b33b8adf79a | 194bc4c60cb49f9f0f48bd16a0e4a595e0f77d4c | refs/heads/master | 2021-01-13T08:00:17.588000 | 2016-10-30T20:18:56 | 2016-10-30T20:18:56 | 70,964,624 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.firstinspires.ftc.teamcode.util.JsonReaders;
import com.qualcomm.ftccommon.DbgLog;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class NavigationOptionsReader extends JsonReader {
String navOptStr;
public JSONObject navOptObj;
public JSONObject lfObj=null;
public JSONObject imuObj=null;
public NavigationOptionsReader(String filePath, String navOptStr) {
super(filePath);
try {
String key = JsonReader.getRealKeyIgnoreCase(jsonRoot, navOptStr);
this.navOptObj = jsonRoot.getJSONObject(key);
key = JsonReader.getRealKeyIgnoreCase(navOptObj, "LineFollow");
if (key != null) {
lfObj = navOptObj.getJSONObject(key);
}
key = JsonReader.getRealKeyIgnoreCase(navOptObj, "IMU");
if (key != null) {
imuObj = navOptObj.getJSONObject(key);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public String getLightSensorName() {
String lightSensorName = null;
JSONObject lightSensorObj;
try {
String key = JsonReader.getRealKeyIgnoreCase(lfObj, "LightSensor");
lightSensorObj = lfObj.getJSONObject(key);
key = JsonReader.getRealKeyIgnoreCase(lightSensorObj, "name");
lightSensorName = lightSensorObj.getString(key);
} catch (JSONException e) {
e.printStackTrace();
}
return (lightSensorName);
}
public String getLightSensorType() {
String sensorType = null;
JSONObject lightSensorObj;
try {
String key = JsonReader.getRealKeyIgnoreCase(lfObj, "LightSensor");
lightSensorObj = lfObj.getJSONObject(key);
key = JsonReader.getRealKeyIgnoreCase(lightSensorObj, "type");
sensorType = lightSensorObj.getString(key);
} catch (JSONException e) {
e.printStackTrace();
}
return (sensorType);
}
public double getLineFollowLowSpeed() {
JSONObject lfVarObj;
double lowSpeed = 0.0;
try {
String key = JsonReader.getRealKeyIgnoreCase(lfObj, "lineFollowVariables");
lfVarObj = lfObj.getJSONObject(key);
key = JsonReader.getRealKeyIgnoreCase(lfVarObj, "lowSpeed");
lowSpeed = lfVarObj.getDouble(key);
} catch (JSONException e) {
e.printStackTrace();
}
return (lowSpeed);
}
public double getLineFollowHighSpeed() {
JSONObject lfVarObj;
double highSpeed = 0.0;
try {
String key = JsonReader.getRealKeyIgnoreCase(lfObj, "lineFollowVariables");
lfVarObj = lfObj.getJSONObject(key);
key = JsonReader.getRealKeyIgnoreCase(lfVarObj, "highSpeed");
highSpeed = lfVarObj.getDouble(key);
} catch (JSONException e) {
e.printStackTrace();
}
return (highSpeed);
}
public double getLineFollowTimeOut() {
double timeoutSec = 0.0;
JSONObject lfVarObj;
try {
String key = JsonReader.getRealKeyIgnoreCase(lfObj, "lineFollowVariables");
lfVarObj = lfObj.getJSONObject(key);
key = JsonReader.getRealKeyIgnoreCase(lfVarObj, "timeOut");
timeoutSec = lfVarObj.getDouble(key);
} catch (JSONException e) {
e.printStackTrace();
}
return (timeoutSec);
}
public String getIMUname() {
String imuName = null;
try {
String key = JsonReader.getRealKeyIgnoreCase(imuObj, "name");
imuName = imuObj.getString(key);
} catch (JSONException e) {
e.printStackTrace();
}
return (imuName);
}
public int getIMUportNum() {
int imuPortNum = 0;
try {
String key = JsonReader.getRealKeyIgnoreCase(imuObj, "portnum");
imuPortNum = imuObj.getInt(key);
} catch (JSONException e) {
e.printStackTrace();
}
return (imuPortNum);
}
}
| UTF-8 | Java | 4,173 | java | NavigationOptionsReader.java | Java | [] | null | [] | package org.firstinspires.ftc.teamcode.util.JsonReaders;
import com.qualcomm.ftccommon.DbgLog;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class NavigationOptionsReader extends JsonReader {
String navOptStr;
public JSONObject navOptObj;
public JSONObject lfObj=null;
public JSONObject imuObj=null;
public NavigationOptionsReader(String filePath, String navOptStr) {
super(filePath);
try {
String key = JsonReader.getRealKeyIgnoreCase(jsonRoot, navOptStr);
this.navOptObj = jsonRoot.getJSONObject(key);
key = JsonReader.getRealKeyIgnoreCase(navOptObj, "LineFollow");
if (key != null) {
lfObj = navOptObj.getJSONObject(key);
}
key = JsonReader.getRealKeyIgnoreCase(navOptObj, "IMU");
if (key != null) {
imuObj = navOptObj.getJSONObject(key);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public String getLightSensorName() {
String lightSensorName = null;
JSONObject lightSensorObj;
try {
String key = JsonReader.getRealKeyIgnoreCase(lfObj, "LightSensor");
lightSensorObj = lfObj.getJSONObject(key);
key = JsonReader.getRealKeyIgnoreCase(lightSensorObj, "name");
lightSensorName = lightSensorObj.getString(key);
} catch (JSONException e) {
e.printStackTrace();
}
return (lightSensorName);
}
public String getLightSensorType() {
String sensorType = null;
JSONObject lightSensorObj;
try {
String key = JsonReader.getRealKeyIgnoreCase(lfObj, "LightSensor");
lightSensorObj = lfObj.getJSONObject(key);
key = JsonReader.getRealKeyIgnoreCase(lightSensorObj, "type");
sensorType = lightSensorObj.getString(key);
} catch (JSONException e) {
e.printStackTrace();
}
return (sensorType);
}
public double getLineFollowLowSpeed() {
JSONObject lfVarObj;
double lowSpeed = 0.0;
try {
String key = JsonReader.getRealKeyIgnoreCase(lfObj, "lineFollowVariables");
lfVarObj = lfObj.getJSONObject(key);
key = JsonReader.getRealKeyIgnoreCase(lfVarObj, "lowSpeed");
lowSpeed = lfVarObj.getDouble(key);
} catch (JSONException e) {
e.printStackTrace();
}
return (lowSpeed);
}
public double getLineFollowHighSpeed() {
JSONObject lfVarObj;
double highSpeed = 0.0;
try {
String key = JsonReader.getRealKeyIgnoreCase(lfObj, "lineFollowVariables");
lfVarObj = lfObj.getJSONObject(key);
key = JsonReader.getRealKeyIgnoreCase(lfVarObj, "highSpeed");
highSpeed = lfVarObj.getDouble(key);
} catch (JSONException e) {
e.printStackTrace();
}
return (highSpeed);
}
public double getLineFollowTimeOut() {
double timeoutSec = 0.0;
JSONObject lfVarObj;
try {
String key = JsonReader.getRealKeyIgnoreCase(lfObj, "lineFollowVariables");
lfVarObj = lfObj.getJSONObject(key);
key = JsonReader.getRealKeyIgnoreCase(lfVarObj, "timeOut");
timeoutSec = lfVarObj.getDouble(key);
} catch (JSONException e) {
e.printStackTrace();
}
return (timeoutSec);
}
public String getIMUname() {
String imuName = null;
try {
String key = JsonReader.getRealKeyIgnoreCase(imuObj, "name");
imuName = imuObj.getString(key);
} catch (JSONException e) {
e.printStackTrace();
}
return (imuName);
}
public int getIMUportNum() {
int imuPortNum = 0;
try {
String key = JsonReader.getRealKeyIgnoreCase(imuObj, "portnum");
imuPortNum = imuObj.getInt(key);
} catch (JSONException e) {
e.printStackTrace();
}
return (imuPortNum);
}
}
| 4,173 | 0.599329 | 0.597652 | 127 | 31.858267 | 23.348682 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.653543 | false | false | 9 |
e08418a9473e08f9f6877b6f03ff410151ae8944 | 28,690,381,577,027 | f81ef9a68711589a799207c81efd6a7816103c69 | /Assignment-2/PalindromeNum.java | 7466af5c7915083dc35e6a6274c7f6aa63390622 | [] | no_license | ayusin51/Hello-Git | https://github.com/ayusin51/Hello-Git | 27ad59945b2b836f7263023d3129e9a51fef0b39 | 8bd5f61545524c7d138ac69cb046e5f54829fdce | refs/heads/master | 2018-10-05T12:35:58.689000 | 2018-06-30T10:46:02 | 2018-06-30T10:46:02 | 136,066,005 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.Scanner;
public class PalindromeNum {
public static boolean palindrome(int num) {
int temp = num;
int rev = 0;
while(temp != 0) {
rev = rev*10 + temp % 10;
temp /= 10;
}
return (rev == num);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
boolean ans = palindrome(num);
System.out.println("The number " + num + " is palindrome : " + ans);
}
}
| UTF-8 | Java | 466 | java | PalindromeNum.java | Java | [] | null | [] | import java.util.Scanner;
public class PalindromeNum {
public static boolean palindrome(int num) {
int temp = num;
int rev = 0;
while(temp != 0) {
rev = rev*10 + temp % 10;
temp /= 10;
}
return (rev == num);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
boolean ans = palindrome(num);
System.out.println("The number " + num + " is palindrome : " + ans);
}
}
| 466 | 0.594421 | 0.577253 | 27 | 16.25926 | 17.506809 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.888889 | false | false | 9 |
6973ae2bfd6df84a88ec51cce7d49302e47e9b33 | 34,076,270,544,503 | 9f3d14e39d069db601f2de111381975d26922b6f | /src/main/java/com/github/teocci/codesample/javafx/threads/ParallelDimension.java | 981406768132a3c55a7c7f1b4adfe45d3a979bd2 | [
"MIT"
] | permissive | teocci/JavaFX-UISamples | https://github.com/teocci/JavaFX-UISamples | 10f725d5950e2e10591b39bdd5303b2c15b26ce2 | aaef171bb3f3ce94b4d80ef3f539d5746d140857 | refs/heads/master | 2022-11-21T02:07:15.868000 | 2019-05-24T05:01:52 | 2019-05-24T05:01:52 | 142,275,267 | 1 | 0 | MIT | false | 2022-11-16T12:21:58 | 2018-07-25T09:04:51 | 2020-07-27T01:37:35 | 2022-11-16T12:21:58 | 15,347 | 1 | 0 | 3 | Java | false | false | package com.github.teocci.codesample.javafx.threads;
import com.github.teocci.codesample.javafx.elements.ShapeMachine;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import javafx.scene.shape.Shape;
/**
* Created by teocci.
*
* @author teocci@yandex.com on 2018-Jul-26
*/
public class ParallelDimension extends Service<ObservableList<Shape>>
{
private final ShapeMachine machine;
private final int nShapes;
public ParallelDimension(ShapeMachine machine, int nShapes)
{
this.machine = machine;
this.nShapes = nShapes;
}
@Override
protected Task<ObservableList<Shape>> createTask()
{
return new Task<ObservableList<Shape>>()
{
@Override
protected ObservableList<Shape> call() throws Exception
{
ObservableList<Shape> shapes = FXCollections.observableArrayList();
for (int i = 0; i < nShapes; i++) {
shapes.add(machine.randomShape());
}
return shapes;
}
};
}
}
| UTF-8 | Java | 1,176 | java | ParallelDimension.java | Java | [
{
"context": "mport javafx.scene.shape.Shape;\n\n/**\n * Created by teocci.\n *\n * @author teocci@yandex.com on 2018-Jul-26\n ",
"end": 326,
"score": 0.998713493347168,
"start": 320,
"tag": "USERNAME",
"value": "teocci"
},
{
"context": "pe.Shape;\n\n/**\n * Created by teocci.\n *\n * @author teocci@yandex.com on 2018-Jul-26\n */\npublic class ParallelDimension",
"end": 359,
"score": 0.9999326467514038,
"start": 342,
"tag": "EMAIL",
"value": "teocci@yandex.com"
}
] | null | [] | package com.github.teocci.codesample.javafx.threads;
import com.github.teocci.codesample.javafx.elements.ShapeMachine;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import javafx.scene.shape.Shape;
/**
* Created by teocci.
*
* @author <EMAIL> on 2018-Jul-26
*/
public class ParallelDimension extends Service<ObservableList<Shape>>
{
private final ShapeMachine machine;
private final int nShapes;
public ParallelDimension(ShapeMachine machine, int nShapes)
{
this.machine = machine;
this.nShapes = nShapes;
}
@Override
protected Task<ObservableList<Shape>> createTask()
{
return new Task<ObservableList<Shape>>()
{
@Override
protected ObservableList<Shape> call() throws Exception
{
ObservableList<Shape> shapes = FXCollections.observableArrayList();
for (int i = 0; i < nShapes; i++) {
shapes.add(machine.randomShape());
}
return shapes;
}
};
}
}
| 1,166 | 0.642857 | 0.636905 | 43 | 26.348837 | 23.272785 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.418605 | false | false | 9 |
e3ba779232656f92f8645410d76efca813f3fe56 | 9,594,956,975,580 | fbac111e4ab094b4c531be20097b8278ea122ad8 | /src/main/java/org/viking/bankett/valhalla/God.java | f9280b5695486c8da99dff714a18198359776780 | [] | no_license | alexishuf/ine5410-t2-20191-initial | https://github.com/alexishuf/ine5410-t2-20191-initial | 189e610b52fb0cb2465509fe84e6d1ab3df83d9f | adce657d02726f54e2a2dafdb6f5abd1fba39692 | refs/heads/master | 2021-07-05T17:37:05.751000 | 2019-06-22T00:06:41 | 2019-06-22T00:06:41 | 190,588,527 | 0 | 0 | null | false | 2020-10-13T13:43:40 | 2019-06-06T13:42:51 | 2019-06-22T00:06:43 | 2020-10-13T13:43:39 | 63 | 0 | 0 | 1 | Java | false | false | package org.viking.bankett.valhalla;
import javax.annotation.Nonnull;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
public enum God {
BALDR {
public @Nonnull Set<God> getRivals() {
return Collections.singleton(LOKI);
}
},
LOKI {
public @Nonnull Set<God> getRivals() {
return Collections.singleton(BALDR);
}
},
VALI {
public @Nonnull Set<God> getRivals() {
return Collections.singleton(HODER);
}
},
HODER {
public @Nonnull Set<God> getRivals() {
return Collections.singleton(VALI);
}
},
FRIGG {
public @Nonnull Set<God> getRivals() {
return Collections.singleton(JORD);
}
},
JORD {
public @Nonnull Set<God> getRivals() {
return Collections.singleton(FRIGG);
}
},
ODIN,
THOR;
private static Set<God> superGods = null;
public static @Nonnull Set<God> getSuperGods() {
if (superGods == null) {
HashSet<God> set = new HashSet<>();
set.add(ODIN);
set.add(THOR);
// a single assignment. May run more than once, but will
// always point to a correct set
superGods = set;
}
return superGods;
}
public @Nonnull Set<God> getRivals() {
return Collections.emptySet();
}
public boolean isSuperGod() {
return this == ODIN || this == THOR;
}
public boolean isRival(God other) {
return this.getRivals().contains(other);
}
}
| UTF-8 | Java | 1,627 | java | God.java | Java | [] | null | [] | package org.viking.bankett.valhalla;
import javax.annotation.Nonnull;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
public enum God {
BALDR {
public @Nonnull Set<God> getRivals() {
return Collections.singleton(LOKI);
}
},
LOKI {
public @Nonnull Set<God> getRivals() {
return Collections.singleton(BALDR);
}
},
VALI {
public @Nonnull Set<God> getRivals() {
return Collections.singleton(HODER);
}
},
HODER {
public @Nonnull Set<God> getRivals() {
return Collections.singleton(VALI);
}
},
FRIGG {
public @Nonnull Set<God> getRivals() {
return Collections.singleton(JORD);
}
},
JORD {
public @Nonnull Set<God> getRivals() {
return Collections.singleton(FRIGG);
}
},
ODIN,
THOR;
private static Set<God> superGods = null;
public static @Nonnull Set<God> getSuperGods() {
if (superGods == null) {
HashSet<God> set = new HashSet<>();
set.add(ODIN);
set.add(THOR);
// a single assignment. May run more than once, but will
// always point to a correct set
superGods = set;
}
return superGods;
}
public @Nonnull Set<God> getRivals() {
return Collections.emptySet();
}
public boolean isSuperGod() {
return this == ODIN || this == THOR;
}
public boolean isRival(God other) {
return this.getRivals().contains(other);
}
}
| 1,627 | 0.552551 | 0.552551 | 67 | 23.283583 | 18.733644 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.462687 | false | false | 9 |
906eaedfcd4fd4087eba209a7af26956bec30407 | 33,887,291,985,664 | 65cdb380d0c3c08b9b35410e745fa4f9511f1609 | /src/main/java/com/sadman/controller/SigningController.java | 626445c601f0b7fbbcf93578b28b9b52fce5bedc | [] | no_license | imran110219/Cryptographic-Tool | https://github.com/imran110219/Cryptographic-Tool | 9415380e557096a03f8b8c80f23d863a0aa4739a | dc9a98ccf39d74016d738ec0cd23a17b29c26163 | refs/heads/master | 2023-02-10T23:09:50.926000 | 2021-01-06T08:58:08 | 2021-01-06T08:58:08 | 324,904,607 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.sadman.controller;
import com.sadman.model.CertificateInfo;
import com.sadman.service.SigningService;
import com.sadman.util.JavaKeyStore;
import com.sadman.util.Util;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.stage.FileChooser;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.jcajce.JcaPEMWriter;
import sun.security.x509.X500Name;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;
import java.security.*;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.*;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.signatures.BouncyCastleDigest;
import com.itextpdf.signatures.DigestAlgorithms;
import com.itextpdf.signatures.IExternalDigest;
import com.itextpdf.signatures.IExternalSignature;
import com.itextpdf.signatures.PdfSignatureAppearance;
import com.itextpdf.signatures.PdfSigner;
import com.itextpdf.signatures.PrivateKeySignature;
/**
* @author Sadman
*/
public class SigningController implements Initializable {
@FXML
ChoiceBox<String> cbFileType;
@FXML
ChoiceBox<CertificateInfo> cbSigner;
@FXML
private Label lblStatus;
private String SRC;
private String DES;
private String ALIAS_NAME;
private String DOCUMENT_TYPE;
JavaKeyStore javaKeyStore;
BouncyCastleProvider provider = new BouncyCastleProvider();
@Override
public void initialize(URL location, ResourceBundle resources) {
Security.addProvider(provider);
ObservableList<String> filetypes = FXCollections.observableArrayList(
"PDF", "Word", "JPG");
cbFileType.setItems(filetypes);
try {
cbSigner.setItems(Util.getCertificates());
javaKeyStore = new JavaKeyStore("PKCS12", "123456", "JavaKeyStore.jks");
javaKeyStore.loadKeyStore();
} catch (CertificateException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
cbSigner.valueProperty().addListener((obs, oldval, newval) -> {
if(newval != null)
ALIAS_NAME = newval.getAliasName();
});
cbFileType.valueProperty().addListener((obs, oldval, newval) -> {
if(newval != null)
DOCUMENT_TYPE = newval;
});
}
@FXML
public void doSelectFile(ActionEvent actionEvent){
FileChooser fileChooser = new FileChooser();
File selectedFile = fileChooser.showOpenDialog(null);
SRC = selectedFile.toString();
}
@FXML
public void doSign(ActionEvent actionEvent) throws GeneralSecurityException, IOException {
DES = "E:/Digidoc/signed.pdf";
Certificate[] chain = javaKeyStore.getCertificateChain(ALIAS_NAME);
PrivateKey privateKey = Util.getPrivateKey(ALIAS_NAME,"123456");
if(DOCUMENT_TYPE.equals("PDF")){
SigningService.signPDF(SRC, DES, chain, privateKey, DigestAlgorithms.SHA256, provider.getName(), PdfSigner.CryptoStandard.CMS, "Test", "Dhaka");
lblStatus.setText("PDF Signed");
lblStatus.setTextFill(Color.GREEN);
}
else {
lblStatus.setText("Not Available");
lblStatus.setTextFill(Color.RED);
}
}
@FXML
public void closeAction(ActionEvent event) {
Platform.exit();
}
}
| UTF-8 | Java | 4,226 | java | SigningController.java | Java | [
{
"context": "df.signatures.PrivateKeySignature;\n\n/**\n * @author Sadman\n */\npublic class SigningController implements Ini",
"end": 1665,
"score": 0.9994004368782043,
"start": 1659,
"tag": "NAME",
"value": "Sadman"
},
{
"context": "teKey privateKey = Util.getPrivateKey(ALIAS_NAME,\"123456\");\n if(DOCUMENT_TYPE.equals(\"PDF\")){\n ",
"end": 3703,
"score": 0.999346911907196,
"start": 3697,
"tag": "KEY",
"value": "123456"
}
] | null | [] | package com.sadman.controller;
import com.sadman.model.CertificateInfo;
import com.sadman.service.SigningService;
import com.sadman.util.JavaKeyStore;
import com.sadman.util.Util;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.stage.FileChooser;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.jcajce.JcaPEMWriter;
import sun.security.x509.X500Name;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;
import java.security.*;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.*;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.signatures.BouncyCastleDigest;
import com.itextpdf.signatures.DigestAlgorithms;
import com.itextpdf.signatures.IExternalDigest;
import com.itextpdf.signatures.IExternalSignature;
import com.itextpdf.signatures.PdfSignatureAppearance;
import com.itextpdf.signatures.PdfSigner;
import com.itextpdf.signatures.PrivateKeySignature;
/**
* @author Sadman
*/
public class SigningController implements Initializable {
@FXML
ChoiceBox<String> cbFileType;
@FXML
ChoiceBox<CertificateInfo> cbSigner;
@FXML
private Label lblStatus;
private String SRC;
private String DES;
private String ALIAS_NAME;
private String DOCUMENT_TYPE;
JavaKeyStore javaKeyStore;
BouncyCastleProvider provider = new BouncyCastleProvider();
@Override
public void initialize(URL location, ResourceBundle resources) {
Security.addProvider(provider);
ObservableList<String> filetypes = FXCollections.observableArrayList(
"PDF", "Word", "JPG");
cbFileType.setItems(filetypes);
try {
cbSigner.setItems(Util.getCertificates());
javaKeyStore = new JavaKeyStore("PKCS12", "123456", "JavaKeyStore.jks");
javaKeyStore.loadKeyStore();
} catch (CertificateException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
cbSigner.valueProperty().addListener((obs, oldval, newval) -> {
if(newval != null)
ALIAS_NAME = newval.getAliasName();
});
cbFileType.valueProperty().addListener((obs, oldval, newval) -> {
if(newval != null)
DOCUMENT_TYPE = newval;
});
}
@FXML
public void doSelectFile(ActionEvent actionEvent){
FileChooser fileChooser = new FileChooser();
File selectedFile = fileChooser.showOpenDialog(null);
SRC = selectedFile.toString();
}
@FXML
public void doSign(ActionEvent actionEvent) throws GeneralSecurityException, IOException {
DES = "E:/Digidoc/signed.pdf";
Certificate[] chain = javaKeyStore.getCertificateChain(ALIAS_NAME);
PrivateKey privateKey = Util.getPrivateKey(ALIAS_NAME,"123456");
if(DOCUMENT_TYPE.equals("PDF")){
SigningService.signPDF(SRC, DES, chain, privateKey, DigestAlgorithms.SHA256, provider.getName(), PdfSigner.CryptoStandard.CMS, "Test", "Dhaka");
lblStatus.setText("PDF Signed");
lblStatus.setTextFill(Color.GREEN);
}
else {
lblStatus.setText("Not Available");
lblStatus.setTextFill(Color.RED);
}
}
@FXML
public void closeAction(ActionEvent event) {
Platform.exit();
}
}
| 4,226 | 0.707998 | 0.701846 | 127 | 32.275589 | 23.342596 | 156 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.771654 | false | false | 9 |
94852ef642ba9c4a08fe473b2d6e7135bd89c8a8 | 36,395,552,872,729 | c065ed1313167be92789f8dabd88c26454066bd2 | /src/main/java/day1/ArrayLearn.java | 012de9940078afd67b6ff146a23a2d9d098af801 | [] | no_license | kavi-1990/Selenium-_TestLeaf | https://github.com/kavi-1990/Selenium-_TestLeaf | 0bf812db5aeb35cb8a0832448bbd7eca02ec704f | 9f73e7616a15a19d4974994c6c0190c9600d8a35 | refs/heads/master | 2020-09-27T11:49:51.077000 | 2019-12-07T12:20:59 | 2019-12-07T12:20:59 | 226,509,394 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package day1;
public class ArrayLearn {
public static void main(String[] args)
{
// TODO Auto-generated method stub
String[] juno= {"Suganya","Kavitha","Jayalakshmi"};
for(int i=0;i<juno.length;i++)
{
if(juno[i].startsWith("S")|| juno[i].endsWith("i"))
{
//System.out.println("gffg");
System.out.println(juno[i]);
}
}
}
}
| UTF-8 | Java | 376 | java | ArrayLearn.java | Java | [
{
"context": "DO Auto-generated method stub\n\n\n\tString[] juno= {\"Suganya\",\"Kavitha\",\"Jayalakshmi\"};\n\t\n\t\n\t\n\t\n\tfor(int i=0;i",
"end": 149,
"score": 0.9997684359550476,
"start": 142,
"tag": "NAME",
"value": "Suganya"
},
{
"context": "nerated method stub\n\n\n\tString[] juno= {\"Suganya\",\"Kavitha\",\"Jayalakshmi\"};\n\t\n\t\n\t\n\t\n\tfor(int i=0;i<juno.leng",
"end": 159,
"score": 0.9997666478157043,
"start": 152,
"tag": "NAME",
"value": "Kavitha"
},
{
"context": "thod stub\n\n\n\tString[] juno= {\"Suganya\",\"Kavitha\",\"Jayalakshmi\"};\n\t\n\t\n\t\n\t\n\tfor(int i=0;i<juno.length;i++)\n\t{\n\t\t\n",
"end": 173,
"score": 0.9997736811637878,
"start": 162,
"tag": "NAME",
"value": "Jayalakshmi"
}
] | null | [] | package day1;
public class ArrayLearn {
public static void main(String[] args)
{
// TODO Auto-generated method stub
String[] juno= {"Suganya","Kavitha","Jayalakshmi"};
for(int i=0;i<juno.length;i++)
{
if(juno[i].startsWith("S")|| juno[i].endsWith("i"))
{
//System.out.println("gffg");
System.out.println(juno[i]);
}
}
}
}
| 376 | 0.577128 | 0.571809 | 31 | 11.129032 | 16.368227 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.580645 | false | false | 9 |
d734c1d11513c2711a0d2751437eb0358e659009 | 17,669,495,521,583 | d1e31ed9598307dc87bda096ff07296409d0452a | /src/main/java/ec/edu/espe/Tutorias/controller/Asistentes.java | b8eca8c55e45a723f29c633be885d68ad138aa89 | [] | no_license | crissl/Tutorias | https://github.com/crissl/Tutorias | ff353b377e18b0b8a54b280110dc0698e5bcffe9 | 042b64c0e756a8d7e9f7012675c1f4c100697cc1 | refs/heads/master | 2021-01-08T08:23:17.767000 | 2020-06-25T18:01:21 | 2020-06-25T18:01:21 | 241,969,661 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ec.edu.espe.Tutorias.controller;
import java.sql.SQLException;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import ec.edu.espe.Tutorias.Vo.AsistentesVo;
import ec.edu.espe.Tutorias.Vo.CampusVo;
import ec.edu.espe.Tutorias.Vo.ConfirmacionAsistenciaVo;
import ec.edu.espe.Tutorias.Vo.DatosDocenteVo;
import ec.edu.espe.Tutorias.Vo.DocenteVo;
import ec.edu.espe.Tutorias.Vo.EstudianteVo;
import ec.edu.espe.Tutorias.Vo.HorarioPlaVo;
import ec.edu.espe.Tutorias.Vo.HorarioSeleccionadoVo;
import ec.edu.espe.Tutorias.Vo.HorarioVo;
import ec.edu.espe.Tutorias.Vo.PlanificacionReforzamientoVo;
import ec.edu.espe.Tutorias.Vo.PlanificacionSeleccionadaVo;
import ec.edu.espe.Tutorias.Vo.ResgistroAsistentesVo;
import ec.edu.espe.Tutorias.Vo.SolicitudVo;
import ec.edu.espe.Tutorias.Vo.TipoPersonaVo;
import ec.edu.espe.Tutorias.Vo.emailEstudio;
import ec.edu.espe.Tutorias.dao.AsistenciaRepository;
import ec.edu.espe.Tutorias.model.Asistencia;
import ec.edu.espe.Tutorias.model.Planificacion;
import ec.edu.espe.Tutorias.util.Mensaje;
import ec.edu.espe.Tutorias.constants.DominiosConstantes;
//@CrossOrigin(origins = "*", allowedHeaders = "*", maxAge = 3600)
@CrossOrigin(origins = { DominiosConstantes.DOMAIN_1, DominiosConstantes.DOMAIN_2})
@RestController
@RequestMapping(DominiosConstantes.context)
public class Asistentes {
@Autowired
private AsistenciaRepository asistenciaRepository;
@Autowired
private SolicitudVo campusRepository;
@Autowired
private SolicitudVo horarioAsistencia;
@Autowired
private SolicitudVo nrcPlanificacion;
@Autowired
private SolicitudVo horarioPlanificacion;
@Autowired
private SolicitudVo registroAsistencia;
@Autowired
private SolicitudVo estudiantesAsisten;
@Autowired
private SolicitudVo estudiantes;
@Autowired
private SolicitudVo docentes;
@Autowired
private SolicitudVo tipoPersonas;
@Autowired
private SolicitudVo datosDocentes;
@Autowired
private SolicitudVo emailEstudiante;
private final Mensaje msg = new Mensaje();
// funcion para listar un asistencia
@RequestMapping(value = "/listarAsistencia", method = RequestMethod.GET)
public ResponseEntity<Asistencia> listarAsistencia() throws SQLException {
List<Asistencia> asistencias = asistenciaRepository.findallAsiste();
if (asistencias.isEmpty()) {
return new ResponseEntity(msg.notfound(), HttpStatus.OK);
} else {
return new ResponseEntity(asistencias, HttpStatus.OK);
}
}
//Funcion que devuelve la asistencia de un estudiante para ser confirmada
@RequestMapping(value = "/buscaIdAsistente/{id}", method = RequestMethod.GET)
public ResponseEntity<Asistencia> buscarAsistencia(@PathVariable int id) {
Asistencia AsistenciaE = asistenciaRepository.findById(id);
return new ResponseEntity(AsistenciaE, HttpStatus.OK);
}
//metodo agregar confirmados
@RequestMapping(value = "/crearAsistencia", method = RequestMethod.POST)
public ResponseEntity<Asistencia> crearAsistencia(@Valid @RequestBody Asistencia asistio) {
int ultimo = asistenciaRepository.findTopByOrderByIdDesc().getId() + 1;
asistio.setId(ultimo);
asistenciaRepository.save(asistio);
return new ResponseEntity(msg.add(), HttpStatus.CREATED);
}
//metodo agregar confirmados
@RequestMapping(value = "/crearAsistenciaLista", method = RequestMethod.POST)
public ResponseEntity<Asistencia> crearAsistenciaList(@Valid @RequestBody List<Asistencia> asistio) {
int ultimo = asistenciaRepository.findTopByOrderByIdDesc().getId();
for (int i = 1; i < asistio.size() + 1; i++) {
asistio.get(i - 1).setId(ultimo + i);
}
asistenciaRepository.saveAll(asistio);
return new ResponseEntity(msg.add(), HttpStatus.CREATED);
}
// Funcion Actualizar un asistencia
@RequestMapping(value = "/actualizarAsistencia", method = RequestMethod.PUT)
public ResponseEntity<Asistencia> actualizarAsistencia(@Valid @RequestBody Asistencia asistencia) throws SQLException {
asistenciaRepository.save(asistencia);
return new ResponseEntity(msg.update(), HttpStatus.OK);
}
@RequestMapping(value = "/editarAsistenciaLista", method = RequestMethod.PUT)
public ResponseEntity<Asistencia> uptAsistenciaList(@Valid @RequestBody List<Asistencia> asistio) {
asistenciaRepository.saveAll(asistio);
return new ResponseEntity(msg.add(), HttpStatus.CREATED);
}
@RequestMapping(value = "/getCampus", method = RequestMethod.GET)
public ResponseEntity getCampus() throws SQLException {
String wi = " WHERE SLBRDEF_BLDG_CODE = SLBBLDG_BLDG_CODE ";
List<CampusVo> campus = campusRepository.getCampus(wi);
return new ResponseEntity(campus, HttpStatus.OK);
}
@RequestMapping(value = "/horario/{campus}/{dia}", method = RequestMethod.GET)
public ResponseEntity getHorario(@PathVariable String campus, @PathVariable String dia) throws SQLException {
String wi = "WHERE SZARPGN_IDREPORT = 'AULAS_'||'" + campus + "' AND SLBRDEF_BLDG_CODE = SZARPGN_CAMPVAR3 AND SLBRDEF_ROOM_NUMBER = SZARPGN_CAMPVAR4 AND SLBRDEF_RMST_CODE = 'AC' AND SLBRDEF_ROOM_TYPE = 'C' AND '" + dia + "' IS NOT NULL ORDER BY 3,4,1";
List<HorarioVo> horario = horarioAsistencia.getHorario(wi);
if (horario.isEmpty()) {
return new ResponseEntity(msg.notfound(), HttpStatus.OK);
} else {
return new ResponseEntity(horario, HttpStatus.OK);
}
}
@RequestMapping(value = "/planificaionReforzamiento/{pidm}", method = RequestMethod.GET)
public ResponseEntity getPlanificaionR(@PathVariable String pidm) throws SQLException {
String wi = "WHERE SIRASGN_PIDM = " + pidm + " \r\n"
+ " AND SIRASGN_TERM_CODE = SSBSECT_TERM_CODE\r\n"
+ " AND SIRASGN_CRN = SSBSECT_CRN\r\n"
+ " AND SSRMEET_TERM_CODE = SSBSECT_TERM_CODE\r\n"
+ " AND SSRMEET_CRN = SSBSECT_CRN \r\n"
// + " AND SSRMEET_MTYP_CODE = 'TUTO' \r\n"
// + " AND SSBSECT_PTRM_END_DATE >= SYSDATE\r\n"
+ " AND SSBSECT_SUBJ_CODE = A.SCBCRSE_SUBJ_CODE\r\n"
+ " AND SSBSECT_CRSE_NUMB = A.SCBCRSE_CRSE_NUMB\r\n"
+ " AND A.SCBCRSE_EFF_TERM = (SELECT MAX( SCBCRSE_EFF_TERM)\r\n"
+ " FROM SCBCRSE\r\n"
+ " WHERE SCBCRSE_SUBJ_CODE = A.SCBCRSE_SUBJ_CODE\r\n"
+ " AND SCBCRSE_CRSE_NUMB = A.SCBCRSE_CRSE_NUMB) ";
List<PlanificacionReforzamientoVo> nrcPlanif = nrcPlanificacion.getPlanificaionR(wi);
return new ResponseEntity(nrcPlanif, HttpStatus.OK);
}
@RequestMapping(value = "/horarioPlanificacion/{campus1}/{dia}/{hora_INICIO}/{hora_FIN}", method = RequestMethod.GET)
public ResponseEntity getHorarioPlanificacion(@PathVariable String campus1, @PathVariable String dia, @PathVariable String hora_INICIO, @PathVariable String hora_FIN) throws SQLException {
System.out.println(campus1 + dia + hora_INICIO + hora_FIN);
String wi = "WHERE SZARPGN_IDREPORT = 'AULAS_'||'" + campus1 + "' AND SLBRDEF_BLDG_CODE = SZARPGN_CAMPVAR3 AND SLBRDEF_ROOM_NUMBER = SZARPGN_CAMPVAR4 AND SLBRDEF_RMST_CODE = 'AC' AND SLBRDEF_ROOM_TYPE = 'C' AND '" + dia + "' IS NOT NULL AND SZARPGN_CAMPVAR7 = '" + hora_INICIO + "' AND SZARPGN_CAMPVAR8 = '" + hora_FIN + "' ";
List<HorarioPlaVo> horarioPlan = horarioPlanificacion.getHorarioPlanificacion(wi);
System.out.println(wi);
return new ResponseEntity(horarioPlan, HttpStatus.OK);
}
@RequestMapping(value = "/registroAsistencia/{codigoPlanificacion}", method = RequestMethod.GET)
public ResponseEntity getRegistroAsistencia(@PathVariable int codigoPlanificacion) throws SQLException {
String wi = "WHERE CODIGO_UZTPLANIF = " + codigoPlanificacion + " ";
List<AsistentesVo> horarioPlan = registroAsistencia.getRegistroAsistencia(wi);
System.out.println(wi);
return new ResponseEntity(horarioPlan, HttpStatus.OK);
}
//funcion actual
@RequestMapping(value = "/registroAsistenciaD/{codigoPlanificacion}", method = RequestMethod.GET)
public ResponseEntity getRegistroAsistenciaAcompanamiento(@PathVariable int codigoPlanificacion) throws SQLException {
List<Asistencia> asistentes = asistenciaRepository.findByCodigoPlanificacion(codigoPlanificacion);
return new ResponseEntity(asistentes, HttpStatus.OK);
}
//Funcion que me retorna una asistencia de un estudiante de esa planificacion
@RequestMapping(value = "/planificacionpidm/{planificacion}/{pidm}", method = RequestMethod.GET)
public ResponseEntity getRegistroAsistenci(@PathVariable int planificacion, @PathVariable int pidm) throws SQLException {
Asistencia usuario = asistenciaRepository.findByCodigoPlanificacionAndPidm(planificacion, pidm);
return new ResponseEntity(usuario, HttpStatus.OK);
}
@RequestMapping(value = "/planificaionSeleccion/{pidm}", method = RequestMethod.GET)
public ResponseEntity getplanificacionSeleccion(@PathVariable String pidm) throws SQLException {
String wi = "WHERE SIRASGN_PIDM = " + pidm + " \r\n"
+ " AND SIRASGN_TERM_CODE = SSBSECT_TERM_CODE\r\n"
+ " AND SIRASGN_CRN = SSBSECT_CRN\r\n"
+ " AND SSRMEET_TERM_CODE = SSBSECT_TERM_CODE\r\n"
+ " AND SSRMEET_CRN = SSBSECT_CRN \r\n"
// + " AND SSRMEET_MTYP_CODE = 'TUTO' \r\n"
+ " AND SSBSECT_PTRM_END_DATE >= SYSDATE\r\n"
+ " AND SSBSECT_SUBJ_CODE = A.SCBCRSE_SUBJ_CODE\r\n"
+ " AND SSBSECT_CRSE_NUMB = A.SCBCRSE_CRSE_NUMB\r\n"
+ " AND A.SCBCRSE_EFF_TERM = (SELECT MAX( SCBCRSE_EFF_TERM)\r\n"
+ " FROM SCBCRSE\r\n"
+ " WHERE SCBCRSE_SUBJ_CODE = A.SCBCRSE_SUBJ_CODE\r\n"
+ " AND SCBCRSE_CRSE_NUMB = A.SCBCRSE_CRSE_NUMB) ";
List<PlanificacionSeleccionadaVo> nrcPlanif = nrcPlanificacion.planificacionSeleccion(wi);
return new ResponseEntity(nrcPlanif, HttpStatus.OK);
}
@RequestMapping(value = "/AulaEscogido/{campus1}/{dia}", method = RequestMethod.GET)
public ResponseEntity AulaEscogido(@PathVariable String campus1, @PathVariable String dia) throws SQLException {
System.out.println(campus1 + dia);
String wi = "WHERE SZARPGN_IDREPORT = 'AULAS_'||'" + campus1 + "' AND SLBRDEF_BLDG_CODE = SZARPGN_CAMPVAR3 AND SLBRDEF_ROOM_NUMBER = SZARPGN_CAMPVAR4 AND SLBRDEF_RMST_CODE = 'AC' AND SLBRDEF_ROOM_TYPE = 'C' AND '" + dia + "' IS NOT NULL ";
List<HorarioSeleccionadoVo> horarioPlan = horarioPlanificacion.AulaEscogido(wi);
System.out.println(wi);
return new ResponseEntity(horarioPlan, HttpStatus.OK);
}
@RequestMapping(value = "/registroAsistentes/{pidm}", method = RequestMethod.GET)
public ResponseEntity getRegistroAsistentes(@PathVariable int pidm) throws SQLException {
String wi = "WHERE SPRIDEN_PIDM=" + pidm + " ";
List<ResgistroAsistentesVo> horarioPlan = estudiantesAsisten.getRegistroAsistentes(wi);
System.out.println(wi);
return new ResponseEntity(horarioPlan, HttpStatus.OK);
}
@RequestMapping(value = "/estudiante/{pidm}", method = RequestMethod.GET)
public ResponseEntity getEstudiante(@PathVariable int pidm) throws SQLException {
String wi = "WHERE SGBSTDN_PIDM = " + pidm + " ";
List<EstudianteVo> estudiante= estudiantes.getEstudiante(wi);
System.out.println(wi);
return new ResponseEntity(estudiante, HttpStatus.OK);
}
@RequestMapping(value = "/docente/{pidm}", method = RequestMethod.GET)
public ResponseEntity getDocente(@PathVariable int pidm) throws SQLException {
String wi = "WHERE SIRASGN_PIDM = " + pidm + " ";
List<DocenteVo> docente = docentes.getDocente(wi);
System.out.println(wi);
return new ResponseEntity(docente, HttpStatus.OK);
}
@RequestMapping(value = "/tipoPersona/{pidm}", method = RequestMethod.GET)
public ResponseEntity getTipoPersona(@PathVariable int pidm) throws SQLException {
String wi = "WHERE PEBEMPL_PIDM =" + pidm + " ";
List<TipoPersonaVo> tipo = tipoPersonas.getTipoPersona(wi);
System.out.println(wi);
return new ResponseEntity(tipo, HttpStatus.OK);
}
@RequestMapping(value = "/datosDocente/{pidm}", method = RequestMethod.GET)
public ResponseEntity getDatosDocente(@PathVariable int pidm) throws SQLException {
String wi = "WHERE GOREMAL.GOREMAL_PIDM = SGRADVR_ADVR_PIDM\r\n" +
"AND GOREMAL.GOREMAL_EMAL_CODE = 'STAN'), '') AS CORREO_INSTITUCIONAL,\r\n" +
"NVL((SELECT DISTINCT MAX (GOREMAL.GOREMAL_EMAIL_ADDRESS)\r\n" +
"FROM GOREMAL\r\n" +
"WHERE GOREMAL.GOREMAL_PIDM = SGRADVR_ADVR_PIDM\r\n" +
"AND GOREMAL.GOREMAL_EMAL_CODE = 'PERS'), '') AS CORREO_PERSONAL\r\n" +
"FROM SGRADVR, SPBPERS\r\n" +
"WHERE SGRADVR_PIDM = " + pidm + "\r\n" +
// "AND SGRADVR_ADVR_CODE = 'TACO'\r\n" +
"AND SGRADVR_ADVR_PIDM = SPBPERS_PIDM";
List<DatosDocenteVo> datosDocente = datosDocentes.getDatosDocente(wi);
System.out.println(wi);
return new ResponseEntity(datosDocente, HttpStatus.OK);
}
@RequestMapping(value = "/datosEstudiante/{pidm}", method = RequestMethod.GET)
public ResponseEntity getEmailEstudiante(@PathVariable int pidm) throws SQLException {
String wi = "WHERE SPRIDEN_PIDM = " + pidm + "";
List<emailEstudio> datosEstudiante = emailEstudiante.getEmailEstudiante(wi);
System.out.println(wi);
return new ResponseEntity(datosEstudiante, HttpStatus.OK);
}
@RequestMapping(value = "/datosDocentes/{pidm}", method = RequestMethod.GET)
public ResponseEntity getDatosDocentes(@PathVariable int pidm) throws SQLException {
String wi = "WHERE GOREMAL.GOREMAL_PIDM = SGRADVR_ADVR_PIDM\r\n" +
"AND GOREMAL.GOREMAL_EMAL_CODE = 'STAN'), '') AS CORREO_INSTITUCIONAL,\r\n" +
"NVL((SELECT DISTINCT MAX (GOREMAL.GOREMAL_EMAIL_ADDRESS)\r\n" +
"FROM GOREMAL\r\n" +
"WHERE GOREMAL.GOREMAL_PIDM = SGRADVR_ADVR_PIDM\r\n" +
"AND GOREMAL.GOREMAL_EMAL_CODE = 'PERS'), '') AS CORREO_PERSONAL\r\n" +
"FROM SGRADVR, SPBPERS\r\n" +
"WHERE SPBPERS_PIDM = " + pidm + "\r\n" +
// "AND SGRADVR_ADVR_CODE = 'TACO'\r\n" +
"AND SGRADVR_ADVR_PIDM = SPBPERS_PIDM";
List<DatosDocenteVo> datosDocente = datosDocentes.getDatosDocentes(wi);
System.out.println(wi);
return new ResponseEntity(datosDocente, HttpStatus.OK);
}
}
| UTF-8 | Java | 15,850 | java | Asistentes.java | Java | [] | null | [] | package ec.edu.espe.Tutorias.controller;
import java.sql.SQLException;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import ec.edu.espe.Tutorias.Vo.AsistentesVo;
import ec.edu.espe.Tutorias.Vo.CampusVo;
import ec.edu.espe.Tutorias.Vo.ConfirmacionAsistenciaVo;
import ec.edu.espe.Tutorias.Vo.DatosDocenteVo;
import ec.edu.espe.Tutorias.Vo.DocenteVo;
import ec.edu.espe.Tutorias.Vo.EstudianteVo;
import ec.edu.espe.Tutorias.Vo.HorarioPlaVo;
import ec.edu.espe.Tutorias.Vo.HorarioSeleccionadoVo;
import ec.edu.espe.Tutorias.Vo.HorarioVo;
import ec.edu.espe.Tutorias.Vo.PlanificacionReforzamientoVo;
import ec.edu.espe.Tutorias.Vo.PlanificacionSeleccionadaVo;
import ec.edu.espe.Tutorias.Vo.ResgistroAsistentesVo;
import ec.edu.espe.Tutorias.Vo.SolicitudVo;
import ec.edu.espe.Tutorias.Vo.TipoPersonaVo;
import ec.edu.espe.Tutorias.Vo.emailEstudio;
import ec.edu.espe.Tutorias.dao.AsistenciaRepository;
import ec.edu.espe.Tutorias.model.Asistencia;
import ec.edu.espe.Tutorias.model.Planificacion;
import ec.edu.espe.Tutorias.util.Mensaje;
import ec.edu.espe.Tutorias.constants.DominiosConstantes;
//@CrossOrigin(origins = "*", allowedHeaders = "*", maxAge = 3600)
@CrossOrigin(origins = { DominiosConstantes.DOMAIN_1, DominiosConstantes.DOMAIN_2})
@RestController
@RequestMapping(DominiosConstantes.context)
public class Asistentes {
@Autowired
private AsistenciaRepository asistenciaRepository;
@Autowired
private SolicitudVo campusRepository;
@Autowired
private SolicitudVo horarioAsistencia;
@Autowired
private SolicitudVo nrcPlanificacion;
@Autowired
private SolicitudVo horarioPlanificacion;
@Autowired
private SolicitudVo registroAsistencia;
@Autowired
private SolicitudVo estudiantesAsisten;
@Autowired
private SolicitudVo estudiantes;
@Autowired
private SolicitudVo docentes;
@Autowired
private SolicitudVo tipoPersonas;
@Autowired
private SolicitudVo datosDocentes;
@Autowired
private SolicitudVo emailEstudiante;
private final Mensaje msg = new Mensaje();
// funcion para listar un asistencia
@RequestMapping(value = "/listarAsistencia", method = RequestMethod.GET)
public ResponseEntity<Asistencia> listarAsistencia() throws SQLException {
List<Asistencia> asistencias = asistenciaRepository.findallAsiste();
if (asistencias.isEmpty()) {
return new ResponseEntity(msg.notfound(), HttpStatus.OK);
} else {
return new ResponseEntity(asistencias, HttpStatus.OK);
}
}
//Funcion que devuelve la asistencia de un estudiante para ser confirmada
@RequestMapping(value = "/buscaIdAsistente/{id}", method = RequestMethod.GET)
public ResponseEntity<Asistencia> buscarAsistencia(@PathVariable int id) {
Asistencia AsistenciaE = asistenciaRepository.findById(id);
return new ResponseEntity(AsistenciaE, HttpStatus.OK);
}
//metodo agregar confirmados
@RequestMapping(value = "/crearAsistencia", method = RequestMethod.POST)
public ResponseEntity<Asistencia> crearAsistencia(@Valid @RequestBody Asistencia asistio) {
int ultimo = asistenciaRepository.findTopByOrderByIdDesc().getId() + 1;
asistio.setId(ultimo);
asistenciaRepository.save(asistio);
return new ResponseEntity(msg.add(), HttpStatus.CREATED);
}
//metodo agregar confirmados
@RequestMapping(value = "/crearAsistenciaLista", method = RequestMethod.POST)
public ResponseEntity<Asistencia> crearAsistenciaList(@Valid @RequestBody List<Asistencia> asistio) {
int ultimo = asistenciaRepository.findTopByOrderByIdDesc().getId();
for (int i = 1; i < asistio.size() + 1; i++) {
asistio.get(i - 1).setId(ultimo + i);
}
asistenciaRepository.saveAll(asistio);
return new ResponseEntity(msg.add(), HttpStatus.CREATED);
}
// Funcion Actualizar un asistencia
@RequestMapping(value = "/actualizarAsistencia", method = RequestMethod.PUT)
public ResponseEntity<Asistencia> actualizarAsistencia(@Valid @RequestBody Asistencia asistencia) throws SQLException {
asistenciaRepository.save(asistencia);
return new ResponseEntity(msg.update(), HttpStatus.OK);
}
@RequestMapping(value = "/editarAsistenciaLista", method = RequestMethod.PUT)
public ResponseEntity<Asistencia> uptAsistenciaList(@Valid @RequestBody List<Asistencia> asistio) {
asistenciaRepository.saveAll(asistio);
return new ResponseEntity(msg.add(), HttpStatus.CREATED);
}
@RequestMapping(value = "/getCampus", method = RequestMethod.GET)
public ResponseEntity getCampus() throws SQLException {
String wi = " WHERE SLBRDEF_BLDG_CODE = SLBBLDG_BLDG_CODE ";
List<CampusVo> campus = campusRepository.getCampus(wi);
return new ResponseEntity(campus, HttpStatus.OK);
}
@RequestMapping(value = "/horario/{campus}/{dia}", method = RequestMethod.GET)
public ResponseEntity getHorario(@PathVariable String campus, @PathVariable String dia) throws SQLException {
String wi = "WHERE SZARPGN_IDREPORT = 'AULAS_'||'" + campus + "' AND SLBRDEF_BLDG_CODE = SZARPGN_CAMPVAR3 AND SLBRDEF_ROOM_NUMBER = SZARPGN_CAMPVAR4 AND SLBRDEF_RMST_CODE = 'AC' AND SLBRDEF_ROOM_TYPE = 'C' AND '" + dia + "' IS NOT NULL ORDER BY 3,4,1";
List<HorarioVo> horario = horarioAsistencia.getHorario(wi);
if (horario.isEmpty()) {
return new ResponseEntity(msg.notfound(), HttpStatus.OK);
} else {
return new ResponseEntity(horario, HttpStatus.OK);
}
}
@RequestMapping(value = "/planificaionReforzamiento/{pidm}", method = RequestMethod.GET)
public ResponseEntity getPlanificaionR(@PathVariable String pidm) throws SQLException {
String wi = "WHERE SIRASGN_PIDM = " + pidm + " \r\n"
+ " AND SIRASGN_TERM_CODE = SSBSECT_TERM_CODE\r\n"
+ " AND SIRASGN_CRN = SSBSECT_CRN\r\n"
+ " AND SSRMEET_TERM_CODE = SSBSECT_TERM_CODE\r\n"
+ " AND SSRMEET_CRN = SSBSECT_CRN \r\n"
// + " AND SSRMEET_MTYP_CODE = 'TUTO' \r\n"
// + " AND SSBSECT_PTRM_END_DATE >= SYSDATE\r\n"
+ " AND SSBSECT_SUBJ_CODE = A.SCBCRSE_SUBJ_CODE\r\n"
+ " AND SSBSECT_CRSE_NUMB = A.SCBCRSE_CRSE_NUMB\r\n"
+ " AND A.SCBCRSE_EFF_TERM = (SELECT MAX( SCBCRSE_EFF_TERM)\r\n"
+ " FROM SCBCRSE\r\n"
+ " WHERE SCBCRSE_SUBJ_CODE = A.SCBCRSE_SUBJ_CODE\r\n"
+ " AND SCBCRSE_CRSE_NUMB = A.SCBCRSE_CRSE_NUMB) ";
List<PlanificacionReforzamientoVo> nrcPlanif = nrcPlanificacion.getPlanificaionR(wi);
return new ResponseEntity(nrcPlanif, HttpStatus.OK);
}
@RequestMapping(value = "/horarioPlanificacion/{campus1}/{dia}/{hora_INICIO}/{hora_FIN}", method = RequestMethod.GET)
public ResponseEntity getHorarioPlanificacion(@PathVariable String campus1, @PathVariable String dia, @PathVariable String hora_INICIO, @PathVariable String hora_FIN) throws SQLException {
System.out.println(campus1 + dia + hora_INICIO + hora_FIN);
String wi = "WHERE SZARPGN_IDREPORT = 'AULAS_'||'" + campus1 + "' AND SLBRDEF_BLDG_CODE = SZARPGN_CAMPVAR3 AND SLBRDEF_ROOM_NUMBER = SZARPGN_CAMPVAR4 AND SLBRDEF_RMST_CODE = 'AC' AND SLBRDEF_ROOM_TYPE = 'C' AND '" + dia + "' IS NOT NULL AND SZARPGN_CAMPVAR7 = '" + hora_INICIO + "' AND SZARPGN_CAMPVAR8 = '" + hora_FIN + "' ";
List<HorarioPlaVo> horarioPlan = horarioPlanificacion.getHorarioPlanificacion(wi);
System.out.println(wi);
return new ResponseEntity(horarioPlan, HttpStatus.OK);
}
@RequestMapping(value = "/registroAsistencia/{codigoPlanificacion}", method = RequestMethod.GET)
public ResponseEntity getRegistroAsistencia(@PathVariable int codigoPlanificacion) throws SQLException {
String wi = "WHERE CODIGO_UZTPLANIF = " + codigoPlanificacion + " ";
List<AsistentesVo> horarioPlan = registroAsistencia.getRegistroAsistencia(wi);
System.out.println(wi);
return new ResponseEntity(horarioPlan, HttpStatus.OK);
}
//funcion actual
@RequestMapping(value = "/registroAsistenciaD/{codigoPlanificacion}", method = RequestMethod.GET)
public ResponseEntity getRegistroAsistenciaAcompanamiento(@PathVariable int codigoPlanificacion) throws SQLException {
List<Asistencia> asistentes = asistenciaRepository.findByCodigoPlanificacion(codigoPlanificacion);
return new ResponseEntity(asistentes, HttpStatus.OK);
}
//Funcion que me retorna una asistencia de un estudiante de esa planificacion
@RequestMapping(value = "/planificacionpidm/{planificacion}/{pidm}", method = RequestMethod.GET)
public ResponseEntity getRegistroAsistenci(@PathVariable int planificacion, @PathVariable int pidm) throws SQLException {
Asistencia usuario = asistenciaRepository.findByCodigoPlanificacionAndPidm(planificacion, pidm);
return new ResponseEntity(usuario, HttpStatus.OK);
}
@RequestMapping(value = "/planificaionSeleccion/{pidm}", method = RequestMethod.GET)
public ResponseEntity getplanificacionSeleccion(@PathVariable String pidm) throws SQLException {
String wi = "WHERE SIRASGN_PIDM = " + pidm + " \r\n"
+ " AND SIRASGN_TERM_CODE = SSBSECT_TERM_CODE\r\n"
+ " AND SIRASGN_CRN = SSBSECT_CRN\r\n"
+ " AND SSRMEET_TERM_CODE = SSBSECT_TERM_CODE\r\n"
+ " AND SSRMEET_CRN = SSBSECT_CRN \r\n"
// + " AND SSRMEET_MTYP_CODE = 'TUTO' \r\n"
+ " AND SSBSECT_PTRM_END_DATE >= SYSDATE\r\n"
+ " AND SSBSECT_SUBJ_CODE = A.SCBCRSE_SUBJ_CODE\r\n"
+ " AND SSBSECT_CRSE_NUMB = A.SCBCRSE_CRSE_NUMB\r\n"
+ " AND A.SCBCRSE_EFF_TERM = (SELECT MAX( SCBCRSE_EFF_TERM)\r\n"
+ " FROM SCBCRSE\r\n"
+ " WHERE SCBCRSE_SUBJ_CODE = A.SCBCRSE_SUBJ_CODE\r\n"
+ " AND SCBCRSE_CRSE_NUMB = A.SCBCRSE_CRSE_NUMB) ";
List<PlanificacionSeleccionadaVo> nrcPlanif = nrcPlanificacion.planificacionSeleccion(wi);
return new ResponseEntity(nrcPlanif, HttpStatus.OK);
}
@RequestMapping(value = "/AulaEscogido/{campus1}/{dia}", method = RequestMethod.GET)
public ResponseEntity AulaEscogido(@PathVariable String campus1, @PathVariable String dia) throws SQLException {
System.out.println(campus1 + dia);
String wi = "WHERE SZARPGN_IDREPORT = 'AULAS_'||'" + campus1 + "' AND SLBRDEF_BLDG_CODE = SZARPGN_CAMPVAR3 AND SLBRDEF_ROOM_NUMBER = SZARPGN_CAMPVAR4 AND SLBRDEF_RMST_CODE = 'AC' AND SLBRDEF_ROOM_TYPE = 'C' AND '" + dia + "' IS NOT NULL ";
List<HorarioSeleccionadoVo> horarioPlan = horarioPlanificacion.AulaEscogido(wi);
System.out.println(wi);
return new ResponseEntity(horarioPlan, HttpStatus.OK);
}
@RequestMapping(value = "/registroAsistentes/{pidm}", method = RequestMethod.GET)
public ResponseEntity getRegistroAsistentes(@PathVariable int pidm) throws SQLException {
String wi = "WHERE SPRIDEN_PIDM=" + pidm + " ";
List<ResgistroAsistentesVo> horarioPlan = estudiantesAsisten.getRegistroAsistentes(wi);
System.out.println(wi);
return new ResponseEntity(horarioPlan, HttpStatus.OK);
}
@RequestMapping(value = "/estudiante/{pidm}", method = RequestMethod.GET)
public ResponseEntity getEstudiante(@PathVariable int pidm) throws SQLException {
String wi = "WHERE SGBSTDN_PIDM = " + pidm + " ";
List<EstudianteVo> estudiante= estudiantes.getEstudiante(wi);
System.out.println(wi);
return new ResponseEntity(estudiante, HttpStatus.OK);
}
@RequestMapping(value = "/docente/{pidm}", method = RequestMethod.GET)
public ResponseEntity getDocente(@PathVariable int pidm) throws SQLException {
String wi = "WHERE SIRASGN_PIDM = " + pidm + " ";
List<DocenteVo> docente = docentes.getDocente(wi);
System.out.println(wi);
return new ResponseEntity(docente, HttpStatus.OK);
}
@RequestMapping(value = "/tipoPersona/{pidm}", method = RequestMethod.GET)
public ResponseEntity getTipoPersona(@PathVariable int pidm) throws SQLException {
String wi = "WHERE PEBEMPL_PIDM =" + pidm + " ";
List<TipoPersonaVo> tipo = tipoPersonas.getTipoPersona(wi);
System.out.println(wi);
return new ResponseEntity(tipo, HttpStatus.OK);
}
@RequestMapping(value = "/datosDocente/{pidm}", method = RequestMethod.GET)
public ResponseEntity getDatosDocente(@PathVariable int pidm) throws SQLException {
String wi = "WHERE GOREMAL.GOREMAL_PIDM = SGRADVR_ADVR_PIDM\r\n" +
"AND GOREMAL.GOREMAL_EMAL_CODE = 'STAN'), '') AS CORREO_INSTITUCIONAL,\r\n" +
"NVL((SELECT DISTINCT MAX (GOREMAL.GOREMAL_EMAIL_ADDRESS)\r\n" +
"FROM GOREMAL\r\n" +
"WHERE GOREMAL.GOREMAL_PIDM = SGRADVR_ADVR_PIDM\r\n" +
"AND GOREMAL.GOREMAL_EMAL_CODE = 'PERS'), '') AS CORREO_PERSONAL\r\n" +
"FROM SGRADVR, SPBPERS\r\n" +
"WHERE SGRADVR_PIDM = " + pidm + "\r\n" +
// "AND SGRADVR_ADVR_CODE = 'TACO'\r\n" +
"AND SGRADVR_ADVR_PIDM = SPBPERS_PIDM";
List<DatosDocenteVo> datosDocente = datosDocentes.getDatosDocente(wi);
System.out.println(wi);
return new ResponseEntity(datosDocente, HttpStatus.OK);
}
@RequestMapping(value = "/datosEstudiante/{pidm}", method = RequestMethod.GET)
public ResponseEntity getEmailEstudiante(@PathVariable int pidm) throws SQLException {
String wi = "WHERE SPRIDEN_PIDM = " + pidm + "";
List<emailEstudio> datosEstudiante = emailEstudiante.getEmailEstudiante(wi);
System.out.println(wi);
return new ResponseEntity(datosEstudiante, HttpStatus.OK);
}
@RequestMapping(value = "/datosDocentes/{pidm}", method = RequestMethod.GET)
public ResponseEntity getDatosDocentes(@PathVariable int pidm) throws SQLException {
String wi = "WHERE GOREMAL.GOREMAL_PIDM = SGRADVR_ADVR_PIDM\r\n" +
"AND GOREMAL.GOREMAL_EMAL_CODE = 'STAN'), '') AS CORREO_INSTITUCIONAL,\r\n" +
"NVL((SELECT DISTINCT MAX (GOREMAL.GOREMAL_EMAIL_ADDRESS)\r\n" +
"FROM GOREMAL\r\n" +
"WHERE GOREMAL.GOREMAL_PIDM = SGRADVR_ADVR_PIDM\r\n" +
"AND GOREMAL.GOREMAL_EMAL_CODE = 'PERS'), '') AS CORREO_PERSONAL\r\n" +
"FROM SGRADVR, SPBPERS\r\n" +
"WHERE SPBPERS_PIDM = " + pidm + "\r\n" +
// "AND SGRADVR_ADVR_CODE = 'TACO'\r\n" +
"AND SGRADVR_ADVR_PIDM = SPBPERS_PIDM";
List<DatosDocenteVo> datosDocente = datosDocentes.getDatosDocentes(wi);
System.out.println(wi);
return new ResponseEntity(datosDocente, HttpStatus.OK);
}
}
| 15,850 | 0.674132 | 0.672303 | 302 | 51.483444 | 40.872578 | 334 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.768212 | false | false | 9 |
aae8c4b0b5d0263713d91517fb395762e547031c | 687,194,807,159 | c9bda5bfabf9870ec17fcda7d5708be71ae48103 | /common/src/main/java/vis/country/stub/response/Quickcheck.java | df32de6c98548c1af84d123b483a49f3a736a3c2 | [] | no_license | AmiraNagi/test | https://github.com/AmiraNagi/test | 0470b35b05889948cf349cb1f596379da867eae1 | cc9b546c9c1dc85f4ae303aafdcc39d1e3d664be | refs/heads/master | 2020-12-02T22:54:40.791000 | 2017-06-23T23:07:56 | 2017-06-23T23:07:56 | 96,202,767 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package vis.country.stub.response;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonFormat;
public class Quickcheck implements Serializable{
private static final long serialVersionUID = 1L;
private List<PackageGroup> packageGroup;
private ChargeGroup[] chargeGroup;
@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="dd.MM.yyyy")
private Date billDate;
private String sum;
private String currency;
public List<PackageGroup> getPackageGroup() {
return packageGroup;
}
public void setPackageGroup(List<PackageGroup> packageGroup) {
this.packageGroup = packageGroup;
}
public ChargeGroup[] getChargeGroup() {
return chargeGroup;
}
public void setChargeGroup(ChargeGroup[] chargeGroup) {
this.chargeGroup = chargeGroup;
}
public Date getBillDate() {
return billDate;
}
public void setBillDate(Date billDate) {
this.billDate = billDate;
}
public String getSum() {
return sum;
}
public void setSum(String sum) {
this.sum = sum;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
@Override
public String toString() {
return "ClassPojo [packageGroup = " + packageGroup + ", chargeGroup = " + chargeGroup + ", billDate = "
+ billDate + ", sum = " + sum + ", currency = " + currency + "]";
}
}
| UTF-8 | Java | 1,405 | java | Quickcheck.java | Java | [] | null | [] | package vis.country.stub.response;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonFormat;
public class Quickcheck implements Serializable{
private static final long serialVersionUID = 1L;
private List<PackageGroup> packageGroup;
private ChargeGroup[] chargeGroup;
@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="dd.MM.yyyy")
private Date billDate;
private String sum;
private String currency;
public List<PackageGroup> getPackageGroup() {
return packageGroup;
}
public void setPackageGroup(List<PackageGroup> packageGroup) {
this.packageGroup = packageGroup;
}
public ChargeGroup[] getChargeGroup() {
return chargeGroup;
}
public void setChargeGroup(ChargeGroup[] chargeGroup) {
this.chargeGroup = chargeGroup;
}
public Date getBillDate() {
return billDate;
}
public void setBillDate(Date billDate) {
this.billDate = billDate;
}
public String getSum() {
return sum;
}
public void setSum(String sum) {
this.sum = sum;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
@Override
public String toString() {
return "ClassPojo [packageGroup = " + packageGroup + ", chargeGroup = " + chargeGroup + ", billDate = "
+ billDate + ", sum = " + sum + ", currency = " + currency + "]";
}
}
| 1,405 | 0.720996 | 0.720285 | 69 | 19.362318 | 21.977571 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.231884 | false | false | 9 |
f4c26b63ef906c1987074b9ec65fbd9bb3a0f2b7 | 15,229,954,065,810 | 08ce0d1af5d24fa29e7015dd7181eed8efb02354 | /src/string/ReverseWordsinaString_151.java | 7464c19fd6b8c17825b6d5055ca6c2f1c39ab73e | [] | no_license | baoxianjian/LeetCode | https://github.com/baoxianjian/LeetCode | 99a0dd2507cd264507901bd6f1dc833c6cd4c665 | 62a29d7dc2b290831f5324f7bd28a2af654208f6 | refs/heads/master | 2020-03-30T21:28:04.296000 | 2019-04-10T16:01:01 | 2019-04-10T16:01:01 | 151,629,548 | 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 string;
/**
*
* @author baoge
*/
public class ReverseWordsinaString_151 {
public String reverseWords(String s) {
if(s==null || s.equals("")){return "";}
//s=s.replaceAll("[ ]+", " ");
String[] words =s.split(" ");
StringBuilder str=new StringBuilder();
for(int i=words.length-1;i>=0;i--)
{
if(words[i].equals("")) {
continue;
}
str.append(words[i]);
str.append(" ");
// str+=words[i]+" ";
}
return str.toString().trim();
}
public static void main(String[] args)
{
String str=new ReverseWordsinaString_151().reverseWords("the sky is bulue");
System.out.println(str);
}
}
| UTF-8 | Java | 974 | java | ReverseWordsinaString_151.java | Java | [
{
"context": "the editor.\n */\npackage string;\n\n/**\n *\n * @author baoge\n */\npublic class ReverseWordsinaString_151 {\n ",
"end": 225,
"score": 0.9994819760322571,
"start": 220,
"tag": "USERNAME",
"value": "baoge"
}
] | 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 string;
/**
*
* @author baoge
*/
public class ReverseWordsinaString_151 {
public String reverseWords(String s) {
if(s==null || s.equals("")){return "";}
//s=s.replaceAll("[ ]+", " ");
String[] words =s.split(" ");
StringBuilder str=new StringBuilder();
for(int i=words.length-1;i>=0;i--)
{
if(words[i].equals("")) {
continue;
}
str.append(words[i]);
str.append(" ");
// str+=words[i]+" ";
}
return str.toString().trim();
}
public static void main(String[] args)
{
String str=new ReverseWordsinaString_151().reverseWords("the sky is bulue");
System.out.println(str);
}
}
| 974 | 0.529774 | 0.521561 | 39 | 23.97436 | 21.815647 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.512821 | false | false | 9 |
9c291032fe5ba652ac873f10214e602a9b7b0079 | 15,229,954,064,224 | f3ef0ac8bd07717d108089c0b29c6d2fe5aad346 | /src/negocio/interfaces/INegocioPessoa.java | a689af0cd7c2638424fc6ed396458fc8a2712f5f | [] | no_license | igorcalbuquerque/SIMarket | https://github.com/igorcalbuquerque/SIMarket | e396f3591b55c189a792c1495e33a0af36e72519 | 7c652e39f4890ccd267fd1a956ab6db163bff338 | refs/heads/master | 2020-03-29T16:17:47.098000 | 2018-12-17T23:17:20 | 2018-12-17T23:17:20 | 150,107,587 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package negocio.interfaces;
import negocio.entidades.abstratas.Pessoa;
import negocio.excecao.*;
public interface INegocioPessoa {
void adicionarPessoa(Pessoa pessoa) throws CpfJaExisteException, RgJaExisteException;
Pessoa buscarPessoaPorCpf(String cpf) throws CpfNaoEncontrado;
Pessoa buscarPessoaPorRg(String cpf) throws RgNaoEncontrado;
String buscarPorNome(String nome) throws PessoaNaoEncotradaException;
void removerPessoaPorRg(String rg) throws RgNaoEncontrado;
void removerPessoaPorCpf(String cpf) throws CpfNaoEncontrado;
}
| UTF-8 | Java | 560 | java | INegocioPessoa.java | Java | [] | null | [] | package negocio.interfaces;
import negocio.entidades.abstratas.Pessoa;
import negocio.excecao.*;
public interface INegocioPessoa {
void adicionarPessoa(Pessoa pessoa) throws CpfJaExisteException, RgJaExisteException;
Pessoa buscarPessoaPorCpf(String cpf) throws CpfNaoEncontrado;
Pessoa buscarPessoaPorRg(String cpf) throws RgNaoEncontrado;
String buscarPorNome(String nome) throws PessoaNaoEncotradaException;
void removerPessoaPorRg(String rg) throws RgNaoEncontrado;
void removerPessoaPorCpf(String cpf) throws CpfNaoEncontrado;
}
| 560 | 0.823214 | 0.823214 | 13 | 42.076923 | 29.03966 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.769231 | false | false | 9 |
5a115d24446e01958a23f24d56609885c074da4c | 33,930,241,651,426 | e6c40acf68ef144544afe5fa6df6a9f391681bb1 | /app/src/main/java/com/example/folb/salmobile/models/LouseCounting.java | b27f9c3b60a92c92538e72e387a0e19db404f6a0 | [] | no_license | Folb/SalMobilev3 | https://github.com/Folb/SalMobilev3 | 2170c69b2df27e2247cbcf2c95cd57408a2abcbf | 0462b1599d62fb24f9930e66b2a9cce47c69127c | refs/heads/master | 2021-01-20T01:33:06.436000 | 2017-04-26T03:14:29 | 2017-04-26T03:14:29 | 89,294,270 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.folb.salmobile.models;
import org.joda.time.DateTime;
import java.util.ArrayList;
import java.util.HashMap;
/**
* Created by folb on 29.03.17.
*/
public class LouseCounting extends ATask {
private String company;
private String location;
private String penNmb;
private String user;
private String comment;
private String timestamp;
private double temperature;
private boolean bucketSet;
private ArrayList<Fish> fishes;
public LouseCounting(String company, String location, String penNmb, String user, boolean bucketSet) {
this.company = company;
this.location = location;
this.penNmb = penNmb;
this.user = user;
this.temperature = -273;
this.bucketSet = bucketSet;
//timestamp = new DateTime(DateTime.now()).toString();
timestamp = "now";
fishes = new ArrayList<>();
fishes.add(new Fish(1));
}
public void addNewFish() {
fishes.add(new Fish(fishes.size() + 1));
}
public void setComment(String comment) {
this.comment = comment;
}
public void setTemperature(double temperature) {
this.temperature = temperature;
}
public String getCompany() {
return company;
}
public String getLocation() {
return location;
}
public String getPenNmb() {
return penNmb;
}
public String getUser() {
return user;
}
public String getComment() {
return comment;
}
public String getTimestamp() {
return timestamp;
}
public double getTemperature() {
return temperature;
}
public ArrayList<Fish> getFishes() {
return fishes;
}
public boolean isBucketSet() {
return bucketSet;
}
public void setBucketSet(boolean bucketSet) {
this.bucketSet = bucketSet;
}
}
| UTF-8 | Java | 1,906 | java | LouseCounting.java | Java | [
{
"context": "List;\nimport java.util.HashMap;\n\n/**\n * Created by folb on 29.03.17.\n */\n\npublic class LouseCounting exte",
"end": 153,
"score": 0.9996309280395508,
"start": 149,
"tag": "USERNAME",
"value": "folb"
}
] | null | [] | package com.example.folb.salmobile.models;
import org.joda.time.DateTime;
import java.util.ArrayList;
import java.util.HashMap;
/**
* Created by folb on 29.03.17.
*/
public class LouseCounting extends ATask {
private String company;
private String location;
private String penNmb;
private String user;
private String comment;
private String timestamp;
private double temperature;
private boolean bucketSet;
private ArrayList<Fish> fishes;
public LouseCounting(String company, String location, String penNmb, String user, boolean bucketSet) {
this.company = company;
this.location = location;
this.penNmb = penNmb;
this.user = user;
this.temperature = -273;
this.bucketSet = bucketSet;
//timestamp = new DateTime(DateTime.now()).toString();
timestamp = "now";
fishes = new ArrayList<>();
fishes.add(new Fish(1));
}
public void addNewFish() {
fishes.add(new Fish(fishes.size() + 1));
}
public void setComment(String comment) {
this.comment = comment;
}
public void setTemperature(double temperature) {
this.temperature = temperature;
}
public String getCompany() {
return company;
}
public String getLocation() {
return location;
}
public String getPenNmb() {
return penNmb;
}
public String getUser() {
return user;
}
public String getComment() {
return comment;
}
public String getTimestamp() {
return timestamp;
}
public double getTemperature() {
return temperature;
}
public ArrayList<Fish> getFishes() {
return fishes;
}
public boolean isBucketSet() {
return bucketSet;
}
public void setBucketSet(boolean bucketSet) {
this.bucketSet = bucketSet;
}
}
| 1,906 | 0.621721 | 0.61595 | 89 | 20.41573 | 18.447502 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.449438 | false | false | 9 |
c9dda61d3b77be4e542cba20b2d82df8783a4cde | 35,905,926,609,218 | 2b3ce9d06a63f826a51b01ac5939d46e0f92a012 | /src/main/java/com/dino/registermodule/service/ForgetPasswordService.java | f9c51c654da2ef337f0281a3c904077cac36ea58 | [] | no_license | api-user/registerAndLoginModule | https://github.com/api-user/registerAndLoginModule | 2754df29794a701ed8c2b43e0cb7ba59bdbb56a9 | de340af3cfe668594cb3a6446414fe3d5f634b43 | refs/heads/master | 2023-03-17T03:02:35.720000 | 2018-09-14T07:37:15 | 2018-09-14T07:37:15 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.dino.registermodule.service;
import com.dino.registermodule.base.NumberConstant;
import com.dino.registermodule.exception.SystemException;
import org.springframework.transaction.annotation.Transactional;
@Transactional(readOnly = false)
public abstract class ForgetPasswordService {
public static boolean NUMBER_FLAG = Boolean.FALSE;
public static int VERIFICATION_CODE_LENGTH = NumberConstant.Int.INT_TEN;
public static String FORGET_PASSWORD_PREFIX = "FORGET_PASSWORD_";
//短信忘记密码
public void shortMessageForgetPassword(String loginMobile,String verificationCode,String password){
throw new SystemException();
}
//邮箱忘记密码
public void mailForgetPassword(String loginMail,String verificationCode,String password){
throw new SystemException();
}
//邮箱发送验证码
public void sendMailVerificationCode(String loginName) {
throw new SystemException();
}
//根据登录名检查用户是否存在
protected abstract boolean checkLoginName(String loginName);
}
| UTF-8 | Java | 1,079 | java | ForgetPasswordService.java | Java | [] | null | [] | package com.dino.registermodule.service;
import com.dino.registermodule.base.NumberConstant;
import com.dino.registermodule.exception.SystemException;
import org.springframework.transaction.annotation.Transactional;
@Transactional(readOnly = false)
public abstract class ForgetPasswordService {
public static boolean NUMBER_FLAG = Boolean.FALSE;
public static int VERIFICATION_CODE_LENGTH = NumberConstant.Int.INT_TEN;
public static String FORGET_PASSWORD_PREFIX = "FORGET_PASSWORD_";
//短信忘记密码
public void shortMessageForgetPassword(String loginMobile,String verificationCode,String password){
throw new SystemException();
}
//邮箱忘记密码
public void mailForgetPassword(String loginMail,String verificationCode,String password){
throw new SystemException();
}
//邮箱发送验证码
public void sendMailVerificationCode(String loginName) {
throw new SystemException();
}
//根据登录名检查用户是否存在
protected abstract boolean checkLoginName(String loginName);
}
| 1,079 | 0.767488 | 0.767488 | 27 | 36.592594 | 29.583853 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.555556 | false | false | 9 |
e0f894a5fd110f7d0a1055b96918ab58ed007758 | 22,608,707,891,008 | 7443b67cf1e7558c54d86e7a9084c444c69b6bc4 | /plugin1/src/main/java/com/dev/lunny/plugin1/Plugin1MainActivity.java | 0bbd884377a05b5a0169732de6a1e677cbc130a6 | [] | no_license | lunny77/hook-plugin-dev | https://github.com/lunny77/hook-plugin-dev | a2838ec7c444a7a3e93664c47412058a4b34cbc3 | dce98d964f44c56d83a61509d4c37010c76cd006 | refs/heads/master | 2020-04-28T20:35:20.767000 | 2019-03-17T03:13:14 | 2019-03-17T03:13:14 | 175,549,793 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.dev.lunny.plugin1;
import android.os.Bundle;
import com.dev.lunny.basecomponent.PluginBaseActivity;
public class Plugin1MainActivity extends PluginBaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_plugin1_main);
}
}
| UTF-8 | Java | 357 | java | Plugin1MainActivity.java | Java | [] | null | [] | package com.dev.lunny.plugin1;
import android.os.Bundle;
import com.dev.lunny.basecomponent.PluginBaseActivity;
public class Plugin1MainActivity extends PluginBaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_plugin1_main);
}
}
| 357 | 0.764706 | 0.756303 | 14 | 24.5 | 23.849977 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.357143 | false | false | 9 |
baa60c483105399c02a97a73e0c2926949af185c | 28,784,870,874,744 | ad583d4069471b5d27be3101ec58a3c1d886f334 | /meal/src/main/java/common/model/http/HttpHelper.java | 407e6df5de7df3edd8b48426d32c098c5817f64e | [] | no_license | Demons15/iot_meal | https://github.com/Demons15/iot_meal | 2de6fc252ae3469b9caa87adb34aa278bdcd03f7 | 6aaf9cc627d8176683a263d1552217164f23038e | refs/heads/master | 2020-12-22T20:02:11.969000 | 2020-01-29T07:50:15 | 2020-01-29T07:50:15 | 222,909,472 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package common.model.http;
import android.content.Context;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;
import javax.inject.Inject;
import javax.inject.Singleton;
import common.constant.NetService;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* http helper负责创建ApiService实例
*/
@Singleton
public class HttpHelper {
private Context context;
private Retrofit mRetrofitClient;
private HashMap<String, Object> mServiceMap;
@Inject
public HttpHelper(Context context) {
this.context = context;
mServiceMap = new HashMap<>();
initRetrofitClient();
}
@SuppressWarnings("unchecked")
public <S> S getService(Class<S> serviceClass) {
if (mServiceMap.containsKey(serviceClass.getName())) {
return (S) mServiceMap.get(serviceClass.getName());
} else {
Object obj = createService(serviceClass, null);
mServiceMap.put(serviceClass.getName(), obj);
return (S) obj;
}
}
@SuppressWarnings("unchecked")
public <S> S getService(Class<S> serviceClass, OkHttpClient client) {
if (mServiceMap.containsKey(serviceClass.getName())) {
return (S) mServiceMap.get(serviceClass.getName());
} else {
Object obj = createService(serviceClass, client);
mServiceMap.put(serviceClass.getName(), obj);
return (S) obj;
}
}
private void initRetrofitClient() {
OkHttpClient httpClient = new OkHttpClient.Builder()
.readTimeout(NetService.HTTP_READ_TIME_OUT, TimeUnit.SECONDS)
.connectTimeout(NetService.HTTP_CONNECT_TIME_OUT, TimeUnit.SECONDS)
.addInterceptor(new BaseInterceptor<>(null, context))
.build();
mRetrofitClient = createRetrofitClient(httpClient);
}
private Retrofit createRetrofitClient(OkHttpClient httpClient) {
Retrofit.Builder client = new Retrofit.Builder()
.client(httpClient);
client.baseUrl(NetService.MEAL_INFO_URL);
client.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create());
return client.build();
}
private <S> S createService(Class<S> serviceClass, OkHttpClient client) {
if (client == null) {
return mRetrofitClient.create(serviceClass);
} else {
return createRetrofitClient(client).create(serviceClass);
}
}
}
| UTF-8 | Java | 2,664 | java | HttpHelper.java | Java | [] | null | [] | package common.model.http;
import android.content.Context;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;
import javax.inject.Inject;
import javax.inject.Singleton;
import common.constant.NetService;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* http helper负责创建ApiService实例
*/
@Singleton
public class HttpHelper {
private Context context;
private Retrofit mRetrofitClient;
private HashMap<String, Object> mServiceMap;
@Inject
public HttpHelper(Context context) {
this.context = context;
mServiceMap = new HashMap<>();
initRetrofitClient();
}
@SuppressWarnings("unchecked")
public <S> S getService(Class<S> serviceClass) {
if (mServiceMap.containsKey(serviceClass.getName())) {
return (S) mServiceMap.get(serviceClass.getName());
} else {
Object obj = createService(serviceClass, null);
mServiceMap.put(serviceClass.getName(), obj);
return (S) obj;
}
}
@SuppressWarnings("unchecked")
public <S> S getService(Class<S> serviceClass, OkHttpClient client) {
if (mServiceMap.containsKey(serviceClass.getName())) {
return (S) mServiceMap.get(serviceClass.getName());
} else {
Object obj = createService(serviceClass, client);
mServiceMap.put(serviceClass.getName(), obj);
return (S) obj;
}
}
private void initRetrofitClient() {
OkHttpClient httpClient = new OkHttpClient.Builder()
.readTimeout(NetService.HTTP_READ_TIME_OUT, TimeUnit.SECONDS)
.connectTimeout(NetService.HTTP_CONNECT_TIME_OUT, TimeUnit.SECONDS)
.addInterceptor(new BaseInterceptor<>(null, context))
.build();
mRetrofitClient = createRetrofitClient(httpClient);
}
private Retrofit createRetrofitClient(OkHttpClient httpClient) {
Retrofit.Builder client = new Retrofit.Builder()
.client(httpClient);
client.baseUrl(NetService.MEAL_INFO_URL);
client.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create());
return client.build();
}
private <S> S createService(Class<S> serviceClass, OkHttpClient client) {
if (client == null) {
return mRetrofitClient.create(serviceClass);
} else {
return createRetrofitClient(client).create(serviceClass);
}
}
}
| 2,664 | 0.661765 | 0.659125 | 84 | 30.571428 | 25.036776 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.511905 | false | false | 9 |
d4c439b498ed448114418907aeb5f2aedb8068e6 | 28,784,870,875,224 | 6974f071bb2a9774e77f0baaaa28346a470cf3a7 | /src/test/java/user/MyTwitterUserTest.java | 7ab6e8223d467395a75f065cf60cee63dca65d6d | [] | no_license | karyna-volokhatiuk/OOP_lab7 | https://github.com/karyna-volokhatiuk/OOP_lab7 | 142d217c0464c8001ed03ac46dd19b77d4513849 | 6da86b5bc559b68f5bcd9c018ba5aa360b51400c | refs/heads/master | 2023-09-03T01:25:06.312000 | 2021-11-17T00:38:31 | 2021-11-17T00:38:31 | 428,843,614 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package user;
import twitter.TwitterUser;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.Date;
import static org.junit.jupiter.api.Assertions.*;
class MyTwitterUserTest {
MyTwitterUser user;
@BeforeEach
void setUp() {
user = new MyTwitterUser(new TwitterUser("dogdog@gmail.com", "Ukraine", new Date()));
}
@Test
void getUserMail() {
assertEquals("dogdog@gmail.com", user.getUserMail());
}
@Test
void getCountry() {
assertEquals("Ukraine", user.getCountry());
}
@Test
void getLastActiveTime() {
long activeTimeMillis = user.getLastActiveTime().getTime();
long currentTime = System.currentTimeMillis();
assertTrue(currentTime >= activeTimeMillis);
}
} | UTF-8 | Java | 803 | java | MyTwitterUserTest.java | Java | [
{
"context": " user = new MyTwitterUser(new TwitterUser(\"dogdog@gmail.com\", \"Ukraine\", new Date()));\n }\n\n @Test\n v",
"end": 347,
"score": 0.9999246001243591,
"start": 331,
"tag": "EMAIL",
"value": "dogdog@gmail.com"
},
{
"context": "st\n void getUserMail() {\n assertEquals(\"dogdog@gmail.com\", user.getUserMail());\n }\n\n @Test\n void ",
"end": 455,
"score": 0.9999246001243591,
"start": 439,
"tag": "EMAIL",
"value": "dogdog@gmail.com"
}
] | null | [] | package user;
import twitter.TwitterUser;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.Date;
import static org.junit.jupiter.api.Assertions.*;
class MyTwitterUserTest {
MyTwitterUser user;
@BeforeEach
void setUp() {
user = new MyTwitterUser(new TwitterUser("<EMAIL>", "Ukraine", new Date()));
}
@Test
void getUserMail() {
assertEquals("<EMAIL>", user.getUserMail());
}
@Test
void getCountry() {
assertEquals("Ukraine", user.getCountry());
}
@Test
void getLastActiveTime() {
long activeTimeMillis = user.getLastActiveTime().getTime();
long currentTime = System.currentTimeMillis();
assertTrue(currentTime >= activeTimeMillis);
}
} | 785 | 0.665006 | 0.665006 | 35 | 21.971428 | 23.16091 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.485714 | false | false | 9 |
d9ca3497a819e0b7ffd88fb5da40f013965b22f9 | 33,861,522,172,625 | b5e44b07eb34ff9e6846ed9d67da8afcdf25cd1d | /coursera/Algorithms/wordnet/SAP.java | ac4c29e76c2f0f25ea0436bf0550b686499ac25d | [] | no_license | sxzh93/playground | https://github.com/sxzh93/playground | bdce5e02bca8fa590b1031d5cddeb770d1a33cb9 | 19ef203f2ed538412563a971ba511b89d7fd319d | refs/heads/master | 2023-09-01T15:15:54.332000 | 2023-08-27T17:16:47 | 2023-08-27T17:16:47 | 85,707,190 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import edu.princeton.cs.algs4.BreadthFirstDirectedPaths;
import edu.princeton.cs.algs4.Digraph;
import edu.princeton.cs.algs4.In;
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;
public class SAP {
private static final int INFINITY = Integer.MAX_VALUE;
private final Digraph digraph;
// Constructor takes a digraph (not necessarily a DAG).
public SAP(Digraph G) {
this.digraph = new Digraph(G);
}
// Length of the shortest ancestral path between v and w; -1 if no such path.
public int length(int v, int w) {
return findSap(new BreadthFirstDirectedPaths(digraph, v),
new BreadthFirstDirectedPaths(digraph, w), /* returnLength= */true);
}
// A common ancestor of v and w that participates in the shortest ancestral
// path; -1 if no such path.
public int ancestor(int v, int w) {
return findSap(new BreadthFirstDirectedPaths(digraph, v),
new BreadthFirstDirectedPaths(digraph, w), /* returnLength= */ false);
}
// Length of the shortest ancestral path between any vertex in v and any vertex
// in w; -1 if no such path.
public int length(Iterable<Integer> v, Iterable<Integer> w) {
try {
return findSap(new BreadthFirstDirectedPaths(digraph, v),
new BreadthFirstDirectedPaths(digraph, w), /* returnLength= */true);
}
catch (IllegalArgumentException e) {
if (e.getMessage().equals("zero vertices")) {
return -1;
}
else {
throw new IllegalArgumentException(e);
}
}
}
// A common ancestor that participates in shortest ancestral path; -1 if no
// such path.
public int ancestor(Iterable<Integer> v, Iterable<Integer> w) {
try {
return findSap(new BreadthFirstDirectedPaths(digraph, v),
new BreadthFirstDirectedPaths(digraph, w), /* returnLength= */ false);
}
catch (IllegalArgumentException e) {
if (e.getMessage().equals("zero vertices")) {
return -1;
}
else {
throw new IllegalArgumentException(e);
}
}
}
// Returns length iff returnLength set to true else returns ancestor.
private int findSap(BreadthFirstDirectedPaths bfsFromV, BreadthFirstDirectedPaths bfsFromW,
boolean returnLength) {
int shortestLength = INFINITY;
int ancestor = -1;
for (int i = 0; i < this.digraph.V(); i++) {
if (bfsFromV.hasPathTo(i) && bfsFromW.hasPathTo(i)) {
int curLength = bfsFromV.distTo(i) + bfsFromW.distTo(i);
if (curLength < shortestLength) {
shortestLength = curLength;
ancestor = i;
}
}
}
if (returnLength) {
return shortestLength < INFINITY ? shortestLength : -1;
}
return ancestor;
}
// Do unit testing of this class.
public static void main(String[] args) {
In in = new In(args[0]);
Digraph digraph = new Digraph(in);
SAP sap = new SAP(digraph);
while (!StdIn.isEmpty()) {
int v = StdIn.readInt();
int w = StdIn.readInt();
int length = sap.length(v, w);
int ancestor = sap.ancestor(v, w);
StdOut.printf("length = %d, ancestor = %d\n", length, ancestor);
}
}
}
| UTF-8 | Java | 3,565 | java | SAP.java | Java | [] | null | [] | import edu.princeton.cs.algs4.BreadthFirstDirectedPaths;
import edu.princeton.cs.algs4.Digraph;
import edu.princeton.cs.algs4.In;
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;
public class SAP {
private static final int INFINITY = Integer.MAX_VALUE;
private final Digraph digraph;
// Constructor takes a digraph (not necessarily a DAG).
public SAP(Digraph G) {
this.digraph = new Digraph(G);
}
// Length of the shortest ancestral path between v and w; -1 if no such path.
public int length(int v, int w) {
return findSap(new BreadthFirstDirectedPaths(digraph, v),
new BreadthFirstDirectedPaths(digraph, w), /* returnLength= */true);
}
// A common ancestor of v and w that participates in the shortest ancestral
// path; -1 if no such path.
public int ancestor(int v, int w) {
return findSap(new BreadthFirstDirectedPaths(digraph, v),
new BreadthFirstDirectedPaths(digraph, w), /* returnLength= */ false);
}
// Length of the shortest ancestral path between any vertex in v and any vertex
// in w; -1 if no such path.
public int length(Iterable<Integer> v, Iterable<Integer> w) {
try {
return findSap(new BreadthFirstDirectedPaths(digraph, v),
new BreadthFirstDirectedPaths(digraph, w), /* returnLength= */true);
}
catch (IllegalArgumentException e) {
if (e.getMessage().equals("zero vertices")) {
return -1;
}
else {
throw new IllegalArgumentException(e);
}
}
}
// A common ancestor that participates in shortest ancestral path; -1 if no
// such path.
public int ancestor(Iterable<Integer> v, Iterable<Integer> w) {
try {
return findSap(new BreadthFirstDirectedPaths(digraph, v),
new BreadthFirstDirectedPaths(digraph, w), /* returnLength= */ false);
}
catch (IllegalArgumentException e) {
if (e.getMessage().equals("zero vertices")) {
return -1;
}
else {
throw new IllegalArgumentException(e);
}
}
}
// Returns length iff returnLength set to true else returns ancestor.
private int findSap(BreadthFirstDirectedPaths bfsFromV, BreadthFirstDirectedPaths bfsFromW,
boolean returnLength) {
int shortestLength = INFINITY;
int ancestor = -1;
for (int i = 0; i < this.digraph.V(); i++) {
if (bfsFromV.hasPathTo(i) && bfsFromW.hasPathTo(i)) {
int curLength = bfsFromV.distTo(i) + bfsFromW.distTo(i);
if (curLength < shortestLength) {
shortestLength = curLength;
ancestor = i;
}
}
}
if (returnLength) {
return shortestLength < INFINITY ? shortestLength : -1;
}
return ancestor;
}
// Do unit testing of this class.
public static void main(String[] args) {
In in = new In(args[0]);
Digraph digraph = new Digraph(in);
SAP sap = new SAP(digraph);
while (!StdIn.isEmpty()) {
int v = StdIn.readInt();
int w = StdIn.readInt();
int length = sap.length(v, w);
int ancestor = sap.ancestor(v, w);
StdOut.printf("length = %d, ancestor = %d\n", length, ancestor);
}
}
}
| 3,565 | 0.576438 | 0.57223 | 96 | 36.135418 | 27.025305 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false | 9 |
740dedd91a37f3b92bb9a3312785062aba204423 | 7,189,775,311,322 | 7279fde9148a372391c1b4315e97a98fa1a09dae | /app/src/main/java/com/example/houshuai/copy360antivirus/App.java | e847fd22345a91bf48e2d6490039b065fba48c2b | [] | no_license | houshuai0816/Copy360Antivirus | https://github.com/houshuai0816/Copy360Antivirus | b90e06400f09853e766896055d0c77038f19e238 | 709e01d068b230a20ffc230a015ea6eb5c76d38e | refs/heads/master | 2021-01-19T07:17:51.788000 | 2016-07-01T11:17:53 | 2016-07-01T11:17:53 | 62,385,604 | 2 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.houshuai.copy360antivirus;
import android.app.Application;
/**
* Created by HouShuai on 2016/7/1.
*/
public class App extends Application{
//APP全局设置
@Override
public void onCreate() {
super.onCreate();
//网络
//数据库
}
}
| UTF-8 | Java | 304 | java | App.java | Java | [
{
"context": "import android.app.Application;\n\n/**\n * Created by HouShuai on 2016/7/1.\n */\n\npublic class App extends Appli",
"end": 107,
"score": 0.9995757937431335,
"start": 99,
"tag": "NAME",
"value": "HouShuai"
}
] | null | [] | package com.example.houshuai.copy360antivirus;
import android.app.Application;
/**
* Created by HouShuai on 2016/7/1.
*/
public class App extends Application{
//APP全局设置
@Override
public void onCreate() {
super.onCreate();
//网络
//数据库
}
}
| 304 | 0.615385 | 0.583916 | 21 | 12.619047 | 14.607488 | 46 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.142857 | false | false | 9 |
374801a05fa4e729aba5ef57c005d4c9a7424367 | 18,992,345,420,645 | e7a2e6bf73413a680e9f2e884aa47cbd3e560f6f | /src/me/botsko/mythos/events/MythosPlayerInteractEvent.java | ef626f5ab1ce3404934bc5b5fffdacbae0594ac4 | [] | no_license | Yllom001/DarkMythos | https://github.com/Yllom001/DarkMythos | a4623aacfd3ff66b80ac81dd0eeee529a0116876 | 3922c24189a0d0e622aa695021c42d9aae4098ee | refs/heads/master | 2021-01-22T06:40:15.567000 | 2012-06-09T06:17:01 | 2012-06-09T06:17:01 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package me.botsko.mythos.events;
import me.botsko.mythos.Mythos;
import me.botsko.mythos.curses.CurseBase;
import me.botsko.mythos.curses.CurseChoice;
import me.botsko.mythos.spells.SpellBase;
import me.botsko.mythos.spells.SpellChoice;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
public class MythosPlayerInteractEvent implements Listener {
private Mythos plugin;
private SpellChoice sc;
private CurseChoice cc;
/**
*
* @param plugin
*/
public MythosPlayerInteractEvent( Mythos plugin ){
this.plugin = plugin;
this.sc = new SpellChoice( plugin );
this.cc = new CurseChoice( plugin );
}
@EventHandler(priority = EventPriority.NORMAL)
public void onPlayerInteractEvent(final PlayerInteractEvent event){
Player player = event.getPlayer();
// Ensure they're right-clicking
if (event.getAction() == Action.RIGHT_CLICK_BLOCK) {
// Ensure they're using a book
if(player.getItemInHand().getType() == Material.BOOK){
// Use the durability to find the award id
SpellBase award = sc.chooseSpell( player.getItemInHand().getDurability() );
if(award != null){
// If the item is cursed, apply the curse and skip using it
CurseBase curse = cc.chooseRandomCurse();
if(curse == null){
// Get the block break award
if( award.useSpellPlayerInteract(event, player) ){
// Message the player
player.sendMessage( plugin.playerMsg( award.getSpellUseMessage() ));
}
} else {
curse.applyCurse(player);
// Tell them about the curse
player.sendMessage( plugin.playerMsg( curse.getMessage() ));
}
}
}
}
}
}
| UTF-8 | Java | 1,903 | java | MythosPlayerInteractEvent.java | Java | [] | null | [] | package me.botsko.mythos.events;
import me.botsko.mythos.Mythos;
import me.botsko.mythos.curses.CurseBase;
import me.botsko.mythos.curses.CurseChoice;
import me.botsko.mythos.spells.SpellBase;
import me.botsko.mythos.spells.SpellChoice;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
public class MythosPlayerInteractEvent implements Listener {
private Mythos plugin;
private SpellChoice sc;
private CurseChoice cc;
/**
*
* @param plugin
*/
public MythosPlayerInteractEvent( Mythos plugin ){
this.plugin = plugin;
this.sc = new SpellChoice( plugin );
this.cc = new CurseChoice( plugin );
}
@EventHandler(priority = EventPriority.NORMAL)
public void onPlayerInteractEvent(final PlayerInteractEvent event){
Player player = event.getPlayer();
// Ensure they're right-clicking
if (event.getAction() == Action.RIGHT_CLICK_BLOCK) {
// Ensure they're using a book
if(player.getItemInHand().getType() == Material.BOOK){
// Use the durability to find the award id
SpellBase award = sc.chooseSpell( player.getItemInHand().getDurability() );
if(award != null){
// If the item is cursed, apply the curse and skip using it
CurseBase curse = cc.chooseRandomCurse();
if(curse == null){
// Get the block break award
if( award.useSpellPlayerInteract(event, player) ){
// Message the player
player.sendMessage( plugin.playerMsg( award.getSpellUseMessage() ));
}
} else {
curse.applyCurse(player);
// Tell them about the curse
player.sendMessage( plugin.playerMsg( curse.getMessage() ));
}
}
}
}
}
}
| 1,903 | 0.691014 | 0.691014 | 72 | 25.430555 | 21.745897 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.888889 | false | false | 9 |
6a87a7d2e31485d4e3c262d91174c9b328d05d36 | 18,992,345,421,578 | 0fbc7017a95985056007da0b9fc33e1662fc8719 | /src/org/GreenTeaScript/SoftwareFaultException.java | 52defbbbe5b3391adfcc575b8769e4cffca54dac | [
"BSD-3-Clause"
] | permissive | OkamotoYuki/GreenTeaScript | https://github.com/OkamotoYuki/GreenTeaScript | c3a3d46c397056fc494583428c3a44811bc525c7 | 9c88dfbf15d5c01f705f40d3735c8b91a8bf0bd9 | refs/heads/master | 2021-04-15T19:06:01.837000 | 2013-12-18T06:18:21 | 2013-12-18T06:18:21 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.GreenTeaScript;
public class SoftwareFaultException extends RuntimeException {
private static final long serialVersionUID = 1L;
public Object ErrorSource;
public SoftwareFaultException/*constructor*/(Object ErrorSource) {
super(ErrorSource.toString());
this.ErrorSource = ErrorSource;
}
public String GetStackTrace() {
String Message = "";
//ifdef JAVA
Message += this.ErrorSource + "\n";
StackTraceElement[] Elements = this.getStackTrace();
for(StackTraceElement e : Elements) {
String MethodName = e.getMethodName();
// System.out.println("*** " + MethodName);
Message += "\tat " + MethodName + "(" + e.getFileName() + ":" + e.getLineNumber() + ")\n";
if(MethodName.equals("main")) {
break;
}
}
//endif VAJA
return Message;
}
}
| UTF-8 | Java | 783 | java | SoftwareFaultException.java | Java | [] | null | [] | package org.GreenTeaScript;
public class SoftwareFaultException extends RuntimeException {
private static final long serialVersionUID = 1L;
public Object ErrorSource;
public SoftwareFaultException/*constructor*/(Object ErrorSource) {
super(ErrorSource.toString());
this.ErrorSource = ErrorSource;
}
public String GetStackTrace() {
String Message = "";
//ifdef JAVA
Message += this.ErrorSource + "\n";
StackTraceElement[] Elements = this.getStackTrace();
for(StackTraceElement e : Elements) {
String MethodName = e.getMethodName();
// System.out.println("*** " + MethodName);
Message += "\tat " + MethodName + "(" + e.getFileName() + ":" + e.getLineNumber() + ")\n";
if(MethodName.equals("main")) {
break;
}
}
//endif VAJA
return Message;
}
}
| 783 | 0.692209 | 0.690932 | 26 | 29.115385 | 23.038975 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.076923 | false | false | 9 |
22d69b1fcdeba973105c8ec60c0b930f2ba3a735 | 764,504,221,800 | 59b4c226b824d85cd9daf8badfd78240e69bedce | /src/com/aioerp/model/reports/finance/AccountsCostRecords.java | 7302f51105ae4876a6117b24a364d450f00e6bcf | [] | no_license | NingKangMing/erpdemo | https://github.com/NingKangMing/erpdemo | fdc11c6b23de89f96ec0736197fe0eadb8d0f973 | 9256cf19679db49b0841401ce5156d22b5b13fa9 | refs/heads/master | 2021-07-09T08:55:34.964000 | 2017-10-09T06:24:12 | 2017-10-09T06:24:12 | 106,242,137 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.aioerp.model.reports.finance;
import com.aioerp.common.procedure.CommonProc;
import com.aioerp.controller.ComFunController;
import com.aioerp.model.BaseDbModel;
import com.aioerp.model.base.Accounts;
import com.aioerp.model.base.Staff;
import com.aioerp.model.sys.end.MonthEnd;
import com.aioerp.model.sys.end.YearEnd;
import com.aioerp.util.DateUtils;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.DbPro;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Record;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
public class AccountsCostRecords
extends BaseDbModel
{
public static final AccountsCostRecords dao = new AccountsCostRecords();
public int getGrade()
{
String pids = getStr("pids");
if (pids == null) {
return 0;
}
String[] pidArra = pids.split("}");
return pidArra.length;
}
public String getBlank()
{
int grade = getGrade() - 1;
String blank = "";
for (int i = 0; i < grade; i++) {
blank = blank + " ";
}
return blank;
}
public Map<String, Object> getPage(String configName, int pageNum, int numPerPage, String listID, Map<String, Object> map, List<String> accTypes)
throws SQLException, Exception
{
String accTypeStr = "";
for (int i = 0; i < accTypes.size(); i++)
{
if (i != 0) {
accTypeStr = accTypeStr + ",";
}
accTypeStr = accTypeStr + (String)accTypes.get(i);
}
if (StringUtils.isBlank(accTypeStr)) {
return new HashMap();
}
List<Integer> accIds = Db.use(configName).query("select id from b_accounts where type in (" + accTypeStr + ")");
Map<String, Class<? extends Model>> alias = new HashMap();
StringBuffer sel = new StringBuffer("select accounts.* ");
StringBuffer sql = new StringBuffer("from b_accounts as accounts");
String monthMoneySql = getMoneySql(map);
Model yearEnd = YearEnd.dao.lastModel(configName);
Map<String, Object> mapY = new HashMap();
if (yearEnd != null)
{
Date startDate = yearEnd.getDate("endDate");
startDate = DateUtils.addDays(startDate, 1);
mapY.put("startDate", DateUtils.format(startDate));
}
String allMoneySql = getMoneySql(mapY);
sel.append(" ,(select sum(money) from (" + monthMoneySql + ") as monthMoney where monthMoney.pids like concat('%{',accounts.id,'}%')) as monthMoneys");
sel.append(" ,(select sum(money) from (" + allMoneySql + ") as allMoney where allMoney.pids like concat('%{',accounts.id,'}%')) as allMoneys");
sql.append(" where 1=1 ");
ComFunController.basePrivsSql(sql, (String)map.get("accountPrivs"), "accounts");
if (accIds.size() > 0)
{
sql.append(" and (");
for (int i = 0; i < accIds.size(); i++) {
if (i == 0) {
sql.append(" accounts.pids like '%{" + accIds.get(i) + "}%'");
} else {
sql.append(" or accounts.pids like '%{" + accIds.get(i) + "}%'");
}
}
sql.append(" )");
}
sql.append(" order by pids");
return aioGetPageManyRecord(configName, listID, pageNum, numPerPage, sel.toString(), sql.toString(), alias, new Object[0]);
}
public List<Record> getList(String configName, Map<String, Object> map, List<String> accTypes)
throws ParseException
{
String accTypeStr = "";
for (int i = 0; i < accTypes.size(); i++)
{
if (i != 0) {
accTypeStr = accTypeStr + ",";
}
accTypeStr = accTypeStr + (String)accTypes.get(i);
}
if (StringUtils.isBlank(accTypeStr)) {
return new ArrayList();
}
List<Integer> accIds = Db.use(configName).query("select id from b_accounts where type in (" + accTypeStr + ")");
StringBuffer sel = new StringBuffer("select accounts.* ");
StringBuffer sql = new StringBuffer(" from b_accounts as accounts");
String monthMoneySql = getMoneySql(map);
Model yearEnd = YearEnd.dao.lastModel(configName);
Map<String, Object> mapY = new HashMap();
if (yearEnd != null)
{
Date startDate = yearEnd.getDate("endDate");
startDate = DateUtils.addDays(startDate, 1);
mapY.put("startDate", DateUtils.format(startDate));
}
String allMoneySql = "";
if ((map != null) && (map.get("isMoney") != null) && ("yes".equals(map.get("isMoney")))) {
allMoneySql = getMoneySql(map);
} else {
allMoneySql = getMoneySql(mapY);
}
sel.append(" ,(select sum(money) from (" + monthMoneySql + ") as monthMoney where monthMoney.pids like concat('%{',accounts.id,'}%')) as monthMoneys");
sel.append(" ,(select sum(money) from (" + allMoneySql + ") as allMoney where allMoney.pids like concat('%{',accounts.id,'}%')) as allMoneys");
if (yearEnd == null) {
sel.append(" ,(select sum(accountsInit.money) from b_accounts as mset left join cw_accounts_init as accountsInit on accountsInit.accountsId = mset.id where mset.pids like concat('%{',accounts.id,'}%')) as setMoneys");
}
sql.append(" where 1=1 ");
if (map != null) {
ComFunController.basePrivsSql(sql, (String)map.get("accountPrivs"), "accounts");
}
if (accIds.size() > 0)
{
sql.append(" and (");
for (int i = 0; i < accIds.size(); i++) {
if (i == 0) {
sql.append(" accounts.pids like '%{" + accIds.get(i) + "}%'");
} else {
sql.append(" or accounts.pids like '%{" + accIds.get(i) + "}%'");
}
}
sql.append(" )");
}
sql.append(" order by pids");
sel.append(sql.toString());
return Db.use(configName).find(sel.toString());
}
public Map<String, Object> getDetailPage(String configName, int pageNum, int numPerPage, String listID, Map<String, Object> map)
throws SQLException, Exception
{
Map<String, Class<? extends Model>> alias = new HashMap();
alias.put("staff", Staff.class);
alias.put("accounts", Accounts.class);
StringBuffer sel = new StringBuffer("select his.*,pay.*");
sel.append(" ,sum(case when pay.type = 0 then pay.payMoney else null end) as addMoney");
sel.append(" ,sum(case when pay.type != 0 then pay.payMoney else null end) as subMoney");
sel.append(" ,billType.name as billTypeName,staff.*,accounts.*");
StringBuffer sql = new StringBuffer(" from bb_billhistory as his");
sql.append(" left join cw_pay_type as pay on his.billId = pay.billId and his.billTypeId = pay.billTypeId");
sql.append(" left join sys_billtype as billType on his.billTypeId = billType.id");
sql.append(" left join b_staff as staff on staff.id = his.staffId");
sql.append(" left join b_accounts as accounts on accounts.id = pay.accountId");
sql.append(" where 1=1");
detailQuery(sql, map);
sql.append(" group by pay.accountId,his.billId,pay.billTypeId");
rank(sql, map);
return aioGetPageManyRecord(configName, listID, pageNum, numPerPage, sel.toString(), sql.toString(), alias, new Object[0]);
}
public Map<String, Object> getDetailPageByPro(String configName, int pageNum, int numPerPage, String listID, Map<String, Object> map)
throws SQLException, Exception
{
Map<String, Class<? extends Model>> alias = new HashMap();
alias.put("staff", Staff.class);
alias.put("accounts", Accounts.class);
CommonProc cwPro = new CommonProc("pro_abc", pageNum, numPerPage, map);
return aioGetPageManyRecord(configName, listID, pageNum, numPerPage, cwPro, alias);
}
public BigDecimal getBeforeMoney(String configName, int pageNum, int numPerPage, Map<String, Object> map)
{
if (pageNum <= 1) {
return BigDecimal.ZERO;
}
int limit = (pageNum - 1) * numPerPage;
StringBuffer sql = new StringBuffer(" select sum(t.money)as money from( ");
sql.append(" select cw.money from cw_accounts_init cw");
sql.append(" LEFT JOIN b_accounts accounts on cw.accountsId = accounts.id where 1=1");
sql.append(" and accounts.pids like '%{" + map.get("accountId") + "}%'");
sql.append(" UNION all");
sql.append(" select sum(case when pay.type = 0 then pay.payMoney else pay.payMoney*-1 end) as money from cw_pay_type as pay");
sql.append(" left join bb_billhistory as his on his.billId = pay.billId and his.billTypeId = pay.billTypeId");
sql.append(" left join b_accounts as accounts on accounts.id = pay.accountId");
sql.append(" where 1=1");
detailBeforeQuery(sql, map);
sql.append(" group by his.recodeDate, pay.accountId,his.billId,pay.billTypeId");
sql.append(" union all");
sql.append(" select sum(case when pay.type = 0 then pay.payMoney else pay.payMoney*-1 end) as money from cw_pay_type as pay");
sql.append(" left join bb_billhistory as his on his.billId = pay.billId and his.billTypeId = pay.billTypeId");
sql.append(" left join b_accounts as accounts on accounts.id = pay.accountId");
sql.append(" where 1=1");
detailQuery(sql, map);
sql.append(" group by pay.accountId,his.billId,pay.billTypeId LIMIT 0," + limit);
rank(sql, map);
sql.append(") as t");
return Db.use(configName).queryBigDecimal(sql.toString());
}
public Record getContrast(String configName, Integer accountId)
throws ParseException
{
if (accountId == null) {
accountId = Integer.valueOf(0);
}
List<Model> monthEndList = MonthEnd.dao.getList(configName);
StringBuffer sel = new StringBuffer("select accounts.* ");
StringBuffer sql = new StringBuffer(" from b_accounts as accounts");
if ((monthEndList != null) && (monthEndList.size() > 0))
{
for (int i = 0; i < monthEndList.size(); i++)
{
Model model = (Model)monthEndList.get(i);
Map<String, Object> map = new HashMap();
map.put("startDate", DateUtils.format(model.getDate("startDate")));
map.put("endDate", DateUtils.format(model.getDate("endDate")));
String monthMoneySql = getMoneySql(map);
sel.append(" ,(select sum(money) from (" + monthMoneySql + ") as monthMoney where monthMoney.pids like concat('%{',accounts.id,'}%')) as monthMoney" + model.getInt("monthCount"));
if (i + 1 == monthEndList.size())
{
map = new HashMap();
Date startDate = model.getDate("endDate");
startDate = DateUtils.addDays(startDate, 1);
map.put("startDate", DateUtils.format(startDate));
monthMoneySql = getMoneySql(map);
sel.append(" ,(select sum(money) from (" + monthMoneySql + ") as monthMoney where monthMoney.pids like concat('%{',accounts.id,'}%')) as monthMoney" + model.getInt("monthCount") + 1);
}
}
}
else
{
Map<String, Object> map = new HashMap();
Model yearEnd = YearEnd.dao.lastModel(configName);
if (yearEnd != null)
{
Date startDate = yearEnd.getDate("endDate");
startDate = DateUtils.addDays(startDate, 1);
map.put("startDate", DateUtils.format(startDate));
}
String monthMoneySql = getMoneySql(map);
sel.append(" ,(select sum(money) from (" + monthMoneySql + ") as monthMoney where monthMoney.pids like concat('%{',accounts.id,'}%')) as monthMoney" + 1);
}
sql.append(" where 1=1 ");
sql.append(" and accounts.id = " + accountId);
sel.append(sql.toString());
return Db.use(configName).findFirst(sel.toString());
}
private void detailQuery(StringBuffer sql, Map<String, Object> map)
{
if (map == null) {
return;
}
if ((map.get("startTime") != null) && (map.get("endTime") != null))
{
sql.append(" and his.recodeDate BETWEEN '" + map.get("startTime") + "' and '" + map.get("endTime") + " 23:59:59'");
}
else
{
if (map.get("startTime") != null) {
sql.append(" and his.recodeDate>='" + map.get("startTime") + "'");
}
if (map.get("endTime") != null) {
sql.append(" and his.recodeDate<='" + map.get("endTime") + " 23:59:59'");
}
}
if (map.get("accountId") != null) {
sql.append(" and accounts.pids like '%{" + map.get("accountId") + "}%'");
}
if ((map.get("isRcw") != null) && (!"".equals(map.get("isRcw")))) {
sql.append(" and his.isRcw = " + map.get("isRcw"));
}
}
private void detailBeforeQuery(StringBuffer sql, Map<String, Object> map)
{
if (map == null) {
return;
}
if (map.get("endTime") != null) {
sql.append(" and his.recodeDate<='" + map.get("startTime") + "'");
}
if (map.get("accountId") != null) {
sql.append(" and accounts.pids like '%{" + map.get("accountId") + "}%'");
}
if ((map.get("isRcw") != null) && (!"".equals(map.get("isRcw")))) {
sql.append(" and his.isRcw = " + map.get("isRcw"));
}
}
private String getMoneySql(Map<String, Object> map)
{
StringBuffer sql = new StringBuffer();
if (map != null)
{
sql.append("select sum(case when cw.type=0 then cw.payMoney else cw.payMoney*-1 end) as money,cw.accountId,account.pids from cw_pay_type as cw");
sql.append(" left join b_accounts as account on account.id = cw.accountId ");
sql.append(" where 1=1");
if (map.get("startDate") != null) {
sql.append(" and cw.payTime >='" + map.get("startDate") + "'");
}
if (map.get("endDate") != null) {
sql.append(" and cw.payTime <='" + map.get("endDate") + " 23:59:59'");
}
}
else
{
sql.append("select (case when sum(case when cw.type=0 then cw.payMoney else cw.payMoney*-1 end) is null then 0 else sum(case when cw.type=0 then cw.payMoney else cw.payMoney*-1 end) end )+ (case when account.money is null then 0 else account.money end) as money,cw.accountId,account.pids from cw_pay_type as cw");
sql.append(" left join b_accounts as account on account.id = cw.accountId ");
}
sql.append(" group by cw.accountId");
return sql.toString();
}
public List<BigDecimal> getAllUnitMoney(String configName, Map<String, Object> map, List<String> accTypes)
throws ParseException
{
String accTypeStr = "";
for (int i = 0; i < accTypes.size(); i++)
{
if (i != 0) {
accTypeStr = accTypeStr + ",";
}
accTypeStr = accTypeStr + (String)accTypes.get(i);
}
List<Integer> accIds = Db.use(configName).query("select id from b_accounts where type in (" + accTypeStr + ")");
StringBuffer sql = new StringBuffer();
Model yearEnd = YearEnd.dao.lastModel(configName);
if ((yearEnd != null) && (map.get("startDate") == null))
{
Date startDate = yearEnd.getDate("endDate");
startDate = DateUtils.addDays(startDate, 1);
map.put("startDate", DateUtils.format(startDate));
}
sql.append("select sum(uncw.money) as money from (");
sql.append("select sum(");
sql.append(" case when cw.type=0 and account.type='000413' then cw.payMoney");
sql.append(" when cw.type=0 and account.type!='000413' then cw.payMoney*-1");
sql.append(" when cw.type!=0 and account.type='000413' then cw.payMoney *-1");
sql.append(" when cw.type!=0 and account.type!='000413' then cw.payMoney");
sql.append(" end) as money,cw.unitId from cw_pay_type as cw");
sql.append(" left join b_accounts as account on account.id = cw.accountId ");
if (map != null)
{
sql.append(" where 1=1");
if (map.get("startDate") != null) {
sql.append(" and cw.payTime >='" + map.get("startDate") + "'");
}
if (map.get("endDate") != null) {
sql.append(" and cw.payTime <='" + map.get("endDate") + " 23:59:59'");
}
}
if (accIds.size() > 0)
{
sql.append(" and (");
for (int i = 0; i < accIds.size(); i++) {
if (i == 0) {
sql.append(" account.pids like '%{" + accIds.get(i) + "}%'");
} else {
sql.append(" or account.pids like '%{" + accIds.get(i) + "}%'");
}
}
sql.append(" )");
}
sql.append(" group by cw.unitId");
sql.append(" UNION ALL");
if (map != null)
{
sql.append(" select sum(");
sql.append(" case when account.type='000413' then cw.money");
sql.append(" when account.type='00013' then cw.money*-1");
sql.append(" end) as money,cw.unitId from cw_accounts_init as cw");
sql.append(" left join b_accounts as account on account.id = cw.accountsId ");
sql.append(" where 1=1");
}
else
{
sql.append("select sum(");
sql.append(" case when account.type='000413' then cw.money");
sql.append(" when account.type='00013' then cw.money*-1");
sql.append(" end) as money,cw.unitId from cw_pay_type as cw");
sql.append(" left join b_accounts as account on account.id = cw.accountsId ");
sql.append(" where 1=1");
}
if (accIds.size() > 0)
{
sql.append(" and (");
for (int i = 0; i < accIds.size(); i++) {
if (i == 0) {
sql.append(" account.pids like '%{" + accIds.get(i) + "}%'");
} else {
sql.append(" or account.pids like '%{" + accIds.get(i) + "}%'");
}
}
sql.append(" )");
}
sql.append(" group by cw.unitId");
sql.append(")as uncw group by uncw.unitId ");
return Db.use(configName).query(sql.toString());
}
private void rank(StringBuffer sql, Map<String, Object> map)
{
if (map == null) {
return;
}
String orderField = (String)map.get("orderField");
String orderDirection = (String)map.get("orderDirection");
if ((StringUtils.isBlank(orderField)) || (StringUtils.isBlank(orderDirection))) {
return;
}
if ("staffCode".equals(orderField)) {
sql.append(" order by staff.code " + orderDirection);
} else if ("staffName".equals(orderField)) {
sql.append(" order by staff.name " + orderDirection);
} else if ("accountsCode".equals(orderField)) {
sql.append(" order by accounts.code " + orderDirection);
} else if ("accountsFullName".equals(orderField)) {
sql.append(" order by accounts.fullName " + orderDirection);
} else {
sql.append(" order by " + orderField + " " + orderDirection);
}
}
}
| UTF-8 | Java | 18,384 | java | AccountsCostRecords.java | Java | [] | null | [] | package com.aioerp.model.reports.finance;
import com.aioerp.common.procedure.CommonProc;
import com.aioerp.controller.ComFunController;
import com.aioerp.model.BaseDbModel;
import com.aioerp.model.base.Accounts;
import com.aioerp.model.base.Staff;
import com.aioerp.model.sys.end.MonthEnd;
import com.aioerp.model.sys.end.YearEnd;
import com.aioerp.util.DateUtils;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.DbPro;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Record;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
public class AccountsCostRecords
extends BaseDbModel
{
public static final AccountsCostRecords dao = new AccountsCostRecords();
public int getGrade()
{
String pids = getStr("pids");
if (pids == null) {
return 0;
}
String[] pidArra = pids.split("}");
return pidArra.length;
}
public String getBlank()
{
int grade = getGrade() - 1;
String blank = "";
for (int i = 0; i < grade; i++) {
blank = blank + " ";
}
return blank;
}
public Map<String, Object> getPage(String configName, int pageNum, int numPerPage, String listID, Map<String, Object> map, List<String> accTypes)
throws SQLException, Exception
{
String accTypeStr = "";
for (int i = 0; i < accTypes.size(); i++)
{
if (i != 0) {
accTypeStr = accTypeStr + ",";
}
accTypeStr = accTypeStr + (String)accTypes.get(i);
}
if (StringUtils.isBlank(accTypeStr)) {
return new HashMap();
}
List<Integer> accIds = Db.use(configName).query("select id from b_accounts where type in (" + accTypeStr + ")");
Map<String, Class<? extends Model>> alias = new HashMap();
StringBuffer sel = new StringBuffer("select accounts.* ");
StringBuffer sql = new StringBuffer("from b_accounts as accounts");
String monthMoneySql = getMoneySql(map);
Model yearEnd = YearEnd.dao.lastModel(configName);
Map<String, Object> mapY = new HashMap();
if (yearEnd != null)
{
Date startDate = yearEnd.getDate("endDate");
startDate = DateUtils.addDays(startDate, 1);
mapY.put("startDate", DateUtils.format(startDate));
}
String allMoneySql = getMoneySql(mapY);
sel.append(" ,(select sum(money) from (" + monthMoneySql + ") as monthMoney where monthMoney.pids like concat('%{',accounts.id,'}%')) as monthMoneys");
sel.append(" ,(select sum(money) from (" + allMoneySql + ") as allMoney where allMoney.pids like concat('%{',accounts.id,'}%')) as allMoneys");
sql.append(" where 1=1 ");
ComFunController.basePrivsSql(sql, (String)map.get("accountPrivs"), "accounts");
if (accIds.size() > 0)
{
sql.append(" and (");
for (int i = 0; i < accIds.size(); i++) {
if (i == 0) {
sql.append(" accounts.pids like '%{" + accIds.get(i) + "}%'");
} else {
sql.append(" or accounts.pids like '%{" + accIds.get(i) + "}%'");
}
}
sql.append(" )");
}
sql.append(" order by pids");
return aioGetPageManyRecord(configName, listID, pageNum, numPerPage, sel.toString(), sql.toString(), alias, new Object[0]);
}
public List<Record> getList(String configName, Map<String, Object> map, List<String> accTypes)
throws ParseException
{
String accTypeStr = "";
for (int i = 0; i < accTypes.size(); i++)
{
if (i != 0) {
accTypeStr = accTypeStr + ",";
}
accTypeStr = accTypeStr + (String)accTypes.get(i);
}
if (StringUtils.isBlank(accTypeStr)) {
return new ArrayList();
}
List<Integer> accIds = Db.use(configName).query("select id from b_accounts where type in (" + accTypeStr + ")");
StringBuffer sel = new StringBuffer("select accounts.* ");
StringBuffer sql = new StringBuffer(" from b_accounts as accounts");
String monthMoneySql = getMoneySql(map);
Model yearEnd = YearEnd.dao.lastModel(configName);
Map<String, Object> mapY = new HashMap();
if (yearEnd != null)
{
Date startDate = yearEnd.getDate("endDate");
startDate = DateUtils.addDays(startDate, 1);
mapY.put("startDate", DateUtils.format(startDate));
}
String allMoneySql = "";
if ((map != null) && (map.get("isMoney") != null) && ("yes".equals(map.get("isMoney")))) {
allMoneySql = getMoneySql(map);
} else {
allMoneySql = getMoneySql(mapY);
}
sel.append(" ,(select sum(money) from (" + monthMoneySql + ") as monthMoney where monthMoney.pids like concat('%{',accounts.id,'}%')) as monthMoneys");
sel.append(" ,(select sum(money) from (" + allMoneySql + ") as allMoney where allMoney.pids like concat('%{',accounts.id,'}%')) as allMoneys");
if (yearEnd == null) {
sel.append(" ,(select sum(accountsInit.money) from b_accounts as mset left join cw_accounts_init as accountsInit on accountsInit.accountsId = mset.id where mset.pids like concat('%{',accounts.id,'}%')) as setMoneys");
}
sql.append(" where 1=1 ");
if (map != null) {
ComFunController.basePrivsSql(sql, (String)map.get("accountPrivs"), "accounts");
}
if (accIds.size() > 0)
{
sql.append(" and (");
for (int i = 0; i < accIds.size(); i++) {
if (i == 0) {
sql.append(" accounts.pids like '%{" + accIds.get(i) + "}%'");
} else {
sql.append(" or accounts.pids like '%{" + accIds.get(i) + "}%'");
}
}
sql.append(" )");
}
sql.append(" order by pids");
sel.append(sql.toString());
return Db.use(configName).find(sel.toString());
}
public Map<String, Object> getDetailPage(String configName, int pageNum, int numPerPage, String listID, Map<String, Object> map)
throws SQLException, Exception
{
Map<String, Class<? extends Model>> alias = new HashMap();
alias.put("staff", Staff.class);
alias.put("accounts", Accounts.class);
StringBuffer sel = new StringBuffer("select his.*,pay.*");
sel.append(" ,sum(case when pay.type = 0 then pay.payMoney else null end) as addMoney");
sel.append(" ,sum(case when pay.type != 0 then pay.payMoney else null end) as subMoney");
sel.append(" ,billType.name as billTypeName,staff.*,accounts.*");
StringBuffer sql = new StringBuffer(" from bb_billhistory as his");
sql.append(" left join cw_pay_type as pay on his.billId = pay.billId and his.billTypeId = pay.billTypeId");
sql.append(" left join sys_billtype as billType on his.billTypeId = billType.id");
sql.append(" left join b_staff as staff on staff.id = his.staffId");
sql.append(" left join b_accounts as accounts on accounts.id = pay.accountId");
sql.append(" where 1=1");
detailQuery(sql, map);
sql.append(" group by pay.accountId,his.billId,pay.billTypeId");
rank(sql, map);
return aioGetPageManyRecord(configName, listID, pageNum, numPerPage, sel.toString(), sql.toString(), alias, new Object[0]);
}
public Map<String, Object> getDetailPageByPro(String configName, int pageNum, int numPerPage, String listID, Map<String, Object> map)
throws SQLException, Exception
{
Map<String, Class<? extends Model>> alias = new HashMap();
alias.put("staff", Staff.class);
alias.put("accounts", Accounts.class);
CommonProc cwPro = new CommonProc("pro_abc", pageNum, numPerPage, map);
return aioGetPageManyRecord(configName, listID, pageNum, numPerPage, cwPro, alias);
}
public BigDecimal getBeforeMoney(String configName, int pageNum, int numPerPage, Map<String, Object> map)
{
if (pageNum <= 1) {
return BigDecimal.ZERO;
}
int limit = (pageNum - 1) * numPerPage;
StringBuffer sql = new StringBuffer(" select sum(t.money)as money from( ");
sql.append(" select cw.money from cw_accounts_init cw");
sql.append(" LEFT JOIN b_accounts accounts on cw.accountsId = accounts.id where 1=1");
sql.append(" and accounts.pids like '%{" + map.get("accountId") + "}%'");
sql.append(" UNION all");
sql.append(" select sum(case when pay.type = 0 then pay.payMoney else pay.payMoney*-1 end) as money from cw_pay_type as pay");
sql.append(" left join bb_billhistory as his on his.billId = pay.billId and his.billTypeId = pay.billTypeId");
sql.append(" left join b_accounts as accounts on accounts.id = pay.accountId");
sql.append(" where 1=1");
detailBeforeQuery(sql, map);
sql.append(" group by his.recodeDate, pay.accountId,his.billId,pay.billTypeId");
sql.append(" union all");
sql.append(" select sum(case when pay.type = 0 then pay.payMoney else pay.payMoney*-1 end) as money from cw_pay_type as pay");
sql.append(" left join bb_billhistory as his on his.billId = pay.billId and his.billTypeId = pay.billTypeId");
sql.append(" left join b_accounts as accounts on accounts.id = pay.accountId");
sql.append(" where 1=1");
detailQuery(sql, map);
sql.append(" group by pay.accountId,his.billId,pay.billTypeId LIMIT 0," + limit);
rank(sql, map);
sql.append(") as t");
return Db.use(configName).queryBigDecimal(sql.toString());
}
public Record getContrast(String configName, Integer accountId)
throws ParseException
{
if (accountId == null) {
accountId = Integer.valueOf(0);
}
List<Model> monthEndList = MonthEnd.dao.getList(configName);
StringBuffer sel = new StringBuffer("select accounts.* ");
StringBuffer sql = new StringBuffer(" from b_accounts as accounts");
if ((monthEndList != null) && (monthEndList.size() > 0))
{
for (int i = 0; i < monthEndList.size(); i++)
{
Model model = (Model)monthEndList.get(i);
Map<String, Object> map = new HashMap();
map.put("startDate", DateUtils.format(model.getDate("startDate")));
map.put("endDate", DateUtils.format(model.getDate("endDate")));
String monthMoneySql = getMoneySql(map);
sel.append(" ,(select sum(money) from (" + monthMoneySql + ") as monthMoney where monthMoney.pids like concat('%{',accounts.id,'}%')) as monthMoney" + model.getInt("monthCount"));
if (i + 1 == monthEndList.size())
{
map = new HashMap();
Date startDate = model.getDate("endDate");
startDate = DateUtils.addDays(startDate, 1);
map.put("startDate", DateUtils.format(startDate));
monthMoneySql = getMoneySql(map);
sel.append(" ,(select sum(money) from (" + monthMoneySql + ") as monthMoney where monthMoney.pids like concat('%{',accounts.id,'}%')) as monthMoney" + model.getInt("monthCount") + 1);
}
}
}
else
{
Map<String, Object> map = new HashMap();
Model yearEnd = YearEnd.dao.lastModel(configName);
if (yearEnd != null)
{
Date startDate = yearEnd.getDate("endDate");
startDate = DateUtils.addDays(startDate, 1);
map.put("startDate", DateUtils.format(startDate));
}
String monthMoneySql = getMoneySql(map);
sel.append(" ,(select sum(money) from (" + monthMoneySql + ") as monthMoney where monthMoney.pids like concat('%{',accounts.id,'}%')) as monthMoney" + 1);
}
sql.append(" where 1=1 ");
sql.append(" and accounts.id = " + accountId);
sel.append(sql.toString());
return Db.use(configName).findFirst(sel.toString());
}
private void detailQuery(StringBuffer sql, Map<String, Object> map)
{
if (map == null) {
return;
}
if ((map.get("startTime") != null) && (map.get("endTime") != null))
{
sql.append(" and his.recodeDate BETWEEN '" + map.get("startTime") + "' and '" + map.get("endTime") + " 23:59:59'");
}
else
{
if (map.get("startTime") != null) {
sql.append(" and his.recodeDate>='" + map.get("startTime") + "'");
}
if (map.get("endTime") != null) {
sql.append(" and his.recodeDate<='" + map.get("endTime") + " 23:59:59'");
}
}
if (map.get("accountId") != null) {
sql.append(" and accounts.pids like '%{" + map.get("accountId") + "}%'");
}
if ((map.get("isRcw") != null) && (!"".equals(map.get("isRcw")))) {
sql.append(" and his.isRcw = " + map.get("isRcw"));
}
}
private void detailBeforeQuery(StringBuffer sql, Map<String, Object> map)
{
if (map == null) {
return;
}
if (map.get("endTime") != null) {
sql.append(" and his.recodeDate<='" + map.get("startTime") + "'");
}
if (map.get("accountId") != null) {
sql.append(" and accounts.pids like '%{" + map.get("accountId") + "}%'");
}
if ((map.get("isRcw") != null) && (!"".equals(map.get("isRcw")))) {
sql.append(" and his.isRcw = " + map.get("isRcw"));
}
}
private String getMoneySql(Map<String, Object> map)
{
StringBuffer sql = new StringBuffer();
if (map != null)
{
sql.append("select sum(case when cw.type=0 then cw.payMoney else cw.payMoney*-1 end) as money,cw.accountId,account.pids from cw_pay_type as cw");
sql.append(" left join b_accounts as account on account.id = cw.accountId ");
sql.append(" where 1=1");
if (map.get("startDate") != null) {
sql.append(" and cw.payTime >='" + map.get("startDate") + "'");
}
if (map.get("endDate") != null) {
sql.append(" and cw.payTime <='" + map.get("endDate") + " 23:59:59'");
}
}
else
{
sql.append("select (case when sum(case when cw.type=0 then cw.payMoney else cw.payMoney*-1 end) is null then 0 else sum(case when cw.type=0 then cw.payMoney else cw.payMoney*-1 end) end )+ (case when account.money is null then 0 else account.money end) as money,cw.accountId,account.pids from cw_pay_type as cw");
sql.append(" left join b_accounts as account on account.id = cw.accountId ");
}
sql.append(" group by cw.accountId");
return sql.toString();
}
public List<BigDecimal> getAllUnitMoney(String configName, Map<String, Object> map, List<String> accTypes)
throws ParseException
{
String accTypeStr = "";
for (int i = 0; i < accTypes.size(); i++)
{
if (i != 0) {
accTypeStr = accTypeStr + ",";
}
accTypeStr = accTypeStr + (String)accTypes.get(i);
}
List<Integer> accIds = Db.use(configName).query("select id from b_accounts where type in (" + accTypeStr + ")");
StringBuffer sql = new StringBuffer();
Model yearEnd = YearEnd.dao.lastModel(configName);
if ((yearEnd != null) && (map.get("startDate") == null))
{
Date startDate = yearEnd.getDate("endDate");
startDate = DateUtils.addDays(startDate, 1);
map.put("startDate", DateUtils.format(startDate));
}
sql.append("select sum(uncw.money) as money from (");
sql.append("select sum(");
sql.append(" case when cw.type=0 and account.type='000413' then cw.payMoney");
sql.append(" when cw.type=0 and account.type!='000413' then cw.payMoney*-1");
sql.append(" when cw.type!=0 and account.type='000413' then cw.payMoney *-1");
sql.append(" when cw.type!=0 and account.type!='000413' then cw.payMoney");
sql.append(" end) as money,cw.unitId from cw_pay_type as cw");
sql.append(" left join b_accounts as account on account.id = cw.accountId ");
if (map != null)
{
sql.append(" where 1=1");
if (map.get("startDate") != null) {
sql.append(" and cw.payTime >='" + map.get("startDate") + "'");
}
if (map.get("endDate") != null) {
sql.append(" and cw.payTime <='" + map.get("endDate") + " 23:59:59'");
}
}
if (accIds.size() > 0)
{
sql.append(" and (");
for (int i = 0; i < accIds.size(); i++) {
if (i == 0) {
sql.append(" account.pids like '%{" + accIds.get(i) + "}%'");
} else {
sql.append(" or account.pids like '%{" + accIds.get(i) + "}%'");
}
}
sql.append(" )");
}
sql.append(" group by cw.unitId");
sql.append(" UNION ALL");
if (map != null)
{
sql.append(" select sum(");
sql.append(" case when account.type='000413' then cw.money");
sql.append(" when account.type='00013' then cw.money*-1");
sql.append(" end) as money,cw.unitId from cw_accounts_init as cw");
sql.append(" left join b_accounts as account on account.id = cw.accountsId ");
sql.append(" where 1=1");
}
else
{
sql.append("select sum(");
sql.append(" case when account.type='000413' then cw.money");
sql.append(" when account.type='00013' then cw.money*-1");
sql.append(" end) as money,cw.unitId from cw_pay_type as cw");
sql.append(" left join b_accounts as account on account.id = cw.accountsId ");
sql.append(" where 1=1");
}
if (accIds.size() > 0)
{
sql.append(" and (");
for (int i = 0; i < accIds.size(); i++) {
if (i == 0) {
sql.append(" account.pids like '%{" + accIds.get(i) + "}%'");
} else {
sql.append(" or account.pids like '%{" + accIds.get(i) + "}%'");
}
}
sql.append(" )");
}
sql.append(" group by cw.unitId");
sql.append(")as uncw group by uncw.unitId ");
return Db.use(configName).query(sql.toString());
}
private void rank(StringBuffer sql, Map<String, Object> map)
{
if (map == null) {
return;
}
String orderField = (String)map.get("orderField");
String orderDirection = (String)map.get("orderDirection");
if ((StringUtils.isBlank(orderField)) || (StringUtils.isBlank(orderDirection))) {
return;
}
if ("staffCode".equals(orderField)) {
sql.append(" order by staff.code " + orderDirection);
} else if ("staffName".equals(orderField)) {
sql.append(" order by staff.name " + orderDirection);
} else if ("accountsCode".equals(orderField)) {
sql.append(" order by accounts.code " + orderDirection);
} else if ("accountsFullName".equals(orderField)) {
sql.append(" order by accounts.fullName " + orderDirection);
} else {
sql.append(" order by " + orderField + " " + orderDirection);
}
}
}
| 18,384 | 0.61597 | 0.607702 | 454 | 39.493393 | 38.080353 | 322 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.872247 | false | false | 9 |
097679ecf4febcc72892645ae7f2fcfcbf29b546 | 25,993,142,134,792 | ce36e83b92b6f2adb2801355e4cc716029dae589 | /practicas/septima/Ejercicio 2/ficheroSeguro.java | de4aa691ee4b7a4df14b59c41dd8096c02eafeb5 | [] | no_license | guilogar/pctr | https://github.com/guilogar/pctr | a29d5da1d179790a08faaf8e84bf267946a6a39b | 4d482ecf1c00e4c11c0b43695f4302976f75dff5 | refs/heads/master | 2020-03-23T02:08:59.891000 | 2020-01-26T20:50:01 | 2020-01-26T20:50:01 | 140,958,772 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.concurrent.Semaphore;
public class ficheroSeguro
{
public static void main (String[] args) {
Semaphore s = new Semaphore(1);
String ficherito = "";
try
{
ficherito = args[0];
} catch(Exception e) { }
for (int i = 0; i < 10; i++)
{
Lector l = new Lector(s, ficherito);
Escritor e = new Escritor(s, ficherito);
l.start();
e.start();
}
}
}
class Lector extends Thread
{
Semaphore s;
private String nombreFichero;
public Lector(Semaphore s, String nombreFichero)
{
this.s = s;
this.nombreFichero = nombreFichero;
}
@Override
public void run()
{
this.leer();
}
private void leer()
{
try {
this.s.acquire();
// Para leer en exclusión mutua
File ruta = new File(this.nombreFichero);
try
{
RandomAccessFile fichero = new RandomAccessFile(ruta, "r");
while(fichero.getFilePointer() <= fichero.length())
System.out.println(fichero.readLine());
fichero.close();
} catch (EOFException e) { }
catch (Exception e) { }
this.s.release();
} catch(Exception e) { }
}
}
class Escritor extends Thread
{
Semaphore s;
private String nombreFichero;
public Escritor(Semaphore s, String nombreFichero)
{
this.s = s;
this.nombreFichero = nombreFichero;
}
@Override
public void run()
{
this.escribir("holi");
}
private void escribir(String w)
{
try {
this.s.acquire();
// Para escribir en exclusión mutua
File ruta = new File(this.nombreFichero);
try
{
RandomAccessFile fichero = new RandomAccessFile(ruta, "rw");
fichero.writeUTF(w);
fichero.close();
} catch (IOException e) { }
this.s.release();
} catch(Exception e) { }
}
}
| UTF-8 | Java | 2,369 | java | ficheroSeguro.java | Java | [] | null | [] | import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.concurrent.Semaphore;
public class ficheroSeguro
{
public static void main (String[] args) {
Semaphore s = new Semaphore(1);
String ficherito = "";
try
{
ficherito = args[0];
} catch(Exception e) { }
for (int i = 0; i < 10; i++)
{
Lector l = new Lector(s, ficherito);
Escritor e = new Escritor(s, ficherito);
l.start();
e.start();
}
}
}
class Lector extends Thread
{
Semaphore s;
private String nombreFichero;
public Lector(Semaphore s, String nombreFichero)
{
this.s = s;
this.nombreFichero = nombreFichero;
}
@Override
public void run()
{
this.leer();
}
private void leer()
{
try {
this.s.acquire();
// Para leer en exclusión mutua
File ruta = new File(this.nombreFichero);
try
{
RandomAccessFile fichero = new RandomAccessFile(ruta, "r");
while(fichero.getFilePointer() <= fichero.length())
System.out.println(fichero.readLine());
fichero.close();
} catch (EOFException e) { }
catch (Exception e) { }
this.s.release();
} catch(Exception e) { }
}
}
class Escritor extends Thread
{
Semaphore s;
private String nombreFichero;
public Escritor(Semaphore s, String nombreFichero)
{
this.s = s;
this.nombreFichero = nombreFichero;
}
@Override
public void run()
{
this.escribir("holi");
}
private void escribir(String w)
{
try {
this.s.acquire();
// Para escribir en exclusión mutua
File ruta = new File(this.nombreFichero);
try
{
RandomAccessFile fichero = new RandomAccessFile(ruta, "rw");
fichero.writeUTF(w);
fichero.close();
} catch (IOException e) { }
this.s.release();
} catch(Exception e) { }
}
}
| 2,369 | 0.495986 | 0.493874 | 102 | 22.205883 | 17.731848 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.411765 | false | false | 9 |
ba7e92c64a4cf533b22680ff07f7e9b360a148b9 | 9,414,568,354,806 | c5e4a4df2e8069f3fcaa6284e99d62c2ec0352b9 | /Dealer.java | c9bc14c054535bd8ac9ad1e1dc86216e092824fd | [] | no_license | mattlourenco27/assignment5 | https://github.com/mattlourenco27/assignment5 | 2c0fe4e17c48cd5db9c1e595e6b24d9868f84cca | 9c3c2fc81c58a048e45b550cb3b7d00845818718 | refs/heads/master | 2020-03-11T05:26:04.143000 | 2018-04-21T14:24:07 | 2018-04-21T14:24:07 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /****************************************************************************
*
* Created by: Matthew Lourenco
* Created on: Apr 2018
* This program is a blueprint for a dealer for a game of blackjack. This
* class runs the entire game and is the class that should be run.
*
****************************************************************************/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class Dealer extends Player {
private Deck deck = new Deck();
private Deck discardPile = new Deck(true);
private ArrayList<User> users = new ArrayList<User>();
private BufferedReader reader = new BufferedReader(new InputStreamReader
(System.in));
public void startGame() {
//This method controls the game
//Get the amout of players
System.out.println("How many players will play?");
String input = "";
try {
//Get user input
input = reader.readLine();
} catch (IOException noInput) {
noInput.printStackTrace();
}
int numberOfPlayers = 1;
try {
//Convert string to Integer
numberOfPlayers = Integer.parseInt(input);
if(numberOfPlayers < 1) {
numberOfPlayers = 1;
}
} catch (NumberFormatException stringInput) {}
for(int player = 0; player < numberOfPlayers; player++) {
users.add(new User());
}
boolean gameEnd = false;
//Keep the game going until everyone runs out of money
while(!gameEnd) {
playOneRound();
for(int user = users.size() - 1; user >= 0; user--) {
if(users.get(user).getMoney() < 2) {
System.out.println(users.get(user).playerName +
" must leave due to insufficient funds");
users.remove(user);
}
}
if(users.size() == 0 || !choice("Do you want to keep playing?")) {
System.out.println("GAME OVER");
gameEnd = true;
}
}
}
private void playOneRound() {
//Plays a round of blackjack
//get bets
String input = "";
for(User user: users) {
System.out.println(user.playerName + " enter your bet:"
+ "\nMoney: $" + user.getMoney());
double bet = 0.0;
while(true) {
try {
//Get user input
input = reader.readLine();
} catch (IOException noInput) {
noInput.printStackTrace();
}
try {
//Convert string to Double
bet = Double.parseDouble(input);
if(bet > user.getMoney()) {
System.out.println("You do not have enough money");
} else if(user.setBet(bet)) {
break;
} else {
System.out.println("Enter a bet greater than $2");
}
} catch (NumberFormatException stringInput) {
System.out.println("Enter a valid number");
}
}
}
//Deal cards
dealCards();
//Initial display
display();
//Ask for insurance if necessary
manageInsurance();
//Force players with naturals to stand
manageNaturals();
//Manage players who double down or split
for(User user: users) {
//Manage split pairs
if(user.getCard(0).getValue().equals(
user.getCard(1).getValue()) &&
user.getMoney() >= user.getBet()) {
System.out.println("----------");
displayPlayer(user);
if(choice("Do you want to split your pair?")) {
user.splitPair();
for(SplitPair pair: user.getSplitPairs()) {
pair.hit(deckPop());
}
}
}
//Manage doubledowns
if(user.getScore() >= 9 && user.getScore() <= 11 &&
user.getMoney() >= user.getBet()) {
System.out.println("----------");
displayPlayer(user);
if(choice("Do you want to double down?")) {
user.doubledown(deckPop());
}
}
}
finishDeal();
//Display Dealer's cards
System.out.println("\n----------\nDealer:");
for(Card card: getCards()) {
System.out.print(card.getFace() + " ");
}
System.out.println("\nScore: " + getScore());
//Start handing out money
//Insurance
if(getCard(0).isAce() && getScore() == 21) {
for(User user: users) {
user.finishInsurance();
}
}
for(User user: users) {
//Split pairs
if(user.isSplit()) {
for(SplitPair pair: user.getSplitPairs()) {
//Split pairs with an ace as their first card
// do not get 1.5X their bet from a blacjack
if(getScore() > 21) {
if(pair.getCard(0).isAce() &&
pair.getScore() == 21) {
pair.recieveReward(pair.getBet() * 2);
} else if(pair.hasNatural()) {
pair.recieveReward(pair.getBet() * 2.5);
} else if(pair.getScore() <= 21) {
pair.recieveReward(pair.getBet() * 2);
} else {
pair.recieveReward(0);
}
} else if(pair.getScore() < getScore()
|| pair.getScore() > 21) {
pair.recieveReward(0);
} else if (pair.getScore() == getScore()) {
pair.recieveReward(pair.getBet());
} else if(pair.getCard(0).isAce() &&
pair.getScore() == 21) {
pair.recieveReward(pair.getBet() * 2);
} else if(pair.hasNatural()) {
pair.recieveReward(pair.getBet() * 2.5);
} else {
pair.recieveReward(pair.getBet() * 2);
}
displaySplit(pair);
discardPile.addCards(pair.hand.removeAll());
}
user.getSplitPairs().clear();
displayPlayer(user);
user.stand = false;
} else {
//Users who have not split
if(getScore() > 21) {
if(user.hasNatural()) {
user.recieveReward(user.getBet() * 2.5);
} else if(user.getScore() <= 21) {
user.recieveReward(user.getBet() * 2);
} else {
user.recieveReward(0);
}
} else if(user.getScore() < getScore()
|| user.getScore() > 21) {
user.recieveReward(0);
} else if (user.getScore() == getScore()) {
user.recieveReward(user.getBet());
} else if(user.hasNatural()) {
user.recieveReward(user.getBet() * 2.5);
} else {
user.recieveReward(user.getBet() * 2);
}
displayPlayer(user);
discardPile.addCards(user.hand.removeAll());
user.stand = false;
}
}
discardPile.addCards(hand.removeAll());
}
private boolean choice(String question) {
//Ask the player a question. Return true if the answer is yes
System.out.println(question);
String input = "";
try {
//Get user input
input = reader.readLine();
} catch (IOException noInput) {
noInput.printStackTrace();
}
return input.toUpperCase().equals("YES") ||
input.toUpperCase().equals("Y");
}
private boolean hitOrStand() {
//Ask the player if they want to hit or stand
String input = "";
while(true) {
System.out.println("Will you hit or stand?");
try {
//Get user input
input = reader.readLine();
} catch (IOException noInput) {
noInput.printStackTrace();
}
if(input.toUpperCase().equals("HIT")) {
return true;
} else if(input.toUpperCase().equals("STAND")) {
return false;
}
}
}
private void displaySplit(SplitPair pair) {
//Print the data from the inputted split pair
System.out.println("\n" + pair.playerName + ":");
for(Card card: pair.getCards()) {
System.out.print(card.getFace() + " ");
}
System.out.println("\nScore: " + pair.getScore() +
"\nBet: $" + pair.getBet());
}
private void displayPlayer(User user) {
//Print the data from the inputted user
if(user.isSplit()) {
for(SplitPair pair: user.getSplitPairs()) {
displaySplit(pair);
}
} else {
System.out.println("\n" + user.playerName + ":");
for(Card card: user.getCards()) {
System.out.print(card.getFace() + " ");
}
System.out.println("\nScore: " + user.getScore() +
"\nMoney: $" + user.getMoney() + "\nBet: $" +
user.getBet() + "\nInsurance: $" +
user.getInsurance());
}
}
private void display() {
//Display the data from all players
System.out.println("\n----------\nDealer:\n" +
getCard(0).getFace() + " " +
getCard(1).getBack());
for(User user: users) {
displayPlayer(user);
}
}
private void dealCards() {
//Deal two cards to each player
for(int deal = 0; deal < 2; deal++) {
hand.add(deckPop());
for(User user: users) {
user.hit(deckPop());
}
}
}
private Card deckPop() {
//Checks if the next card is a blank and pops a card
if(deck.nextIsBlank()) {
deck.pop();
deck.refill(discardPile);
}
return deck.pop();
}
private void finishDeal() {
//Ask each player if they would like to hit until they all stand
for(User user: users) {
//Deal to split pairs
if(user.isSplit()) {
for(SplitPair split: user.getSplitPairs()) {
while(!split.stand) {
System.out.println("----------");
displaySplit(split);
if(hitOrStand()) {
split.hit(deckPop());
if(split.stand && !split.getCard(0).isAce()) {
displaySplit(split);
System.out.println("You have gone bust");
}
} else {
split.stand();
}
}
}
}
while(!user.stand) {
System.out.println("----------");
displayPlayer(user);
if(hitOrStand()) {
user.hit(deckPop());
if(user.stand) {
displayPlayer(user);
System.out.println("You have gone bust");
}
} else {
user.stand();
}
}
}
//Force the dealer to hit until they have a score of 17+
while(getScore() < 17) {
hand.add(deckPop());
}
}
private void manageNaturals() {
//Force the player to stand if he has a natural
for(User user: users) {
if(user.hasNatural()) {
System.out.println("----------\n" + user.playerName
+ " has 21");
user.stand();
}
}
}
private void manageInsurance() {
//Manage any players who wich to put down insurance
if(getCard(0).isAce()) {
for(User user: users) {
if(user.getMoney() >= user.getBet() / 2) {
System.out.println("----------");
displayPlayer(user);
if(choice("Do you want to put down insurance?")) {
user.addInsurance();
}
}
}
}
}
public static void main(String[] args) {
//Instantiate a dealer and start the game
Dealer dealer = new Dealer();
dealer.startGame();
}
} | UTF-8 | Java | 10,477 | java | Dealer.java | Java | [
{
"context": "******************************\r\n *\r\n * Created by: Matthew Lourenco\r\n * Created on: Apr 2018\r\n * This program is a bl",
"end": 114,
"score": 0.9998717308044434,
"start": 98,
"tag": "NAME",
"value": "Matthew Lourenco"
}
] | null | [] | /****************************************************************************
*
* Created by: <NAME>
* Created on: Apr 2018
* This program is a blueprint for a dealer for a game of blackjack. This
* class runs the entire game and is the class that should be run.
*
****************************************************************************/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class Dealer extends Player {
private Deck deck = new Deck();
private Deck discardPile = new Deck(true);
private ArrayList<User> users = new ArrayList<User>();
private BufferedReader reader = new BufferedReader(new InputStreamReader
(System.in));
public void startGame() {
//This method controls the game
//Get the amout of players
System.out.println("How many players will play?");
String input = "";
try {
//Get user input
input = reader.readLine();
} catch (IOException noInput) {
noInput.printStackTrace();
}
int numberOfPlayers = 1;
try {
//Convert string to Integer
numberOfPlayers = Integer.parseInt(input);
if(numberOfPlayers < 1) {
numberOfPlayers = 1;
}
} catch (NumberFormatException stringInput) {}
for(int player = 0; player < numberOfPlayers; player++) {
users.add(new User());
}
boolean gameEnd = false;
//Keep the game going until everyone runs out of money
while(!gameEnd) {
playOneRound();
for(int user = users.size() - 1; user >= 0; user--) {
if(users.get(user).getMoney() < 2) {
System.out.println(users.get(user).playerName +
" must leave due to insufficient funds");
users.remove(user);
}
}
if(users.size() == 0 || !choice("Do you want to keep playing?")) {
System.out.println("GAME OVER");
gameEnd = true;
}
}
}
private void playOneRound() {
//Plays a round of blackjack
//get bets
String input = "";
for(User user: users) {
System.out.println(user.playerName + " enter your bet:"
+ "\nMoney: $" + user.getMoney());
double bet = 0.0;
while(true) {
try {
//Get user input
input = reader.readLine();
} catch (IOException noInput) {
noInput.printStackTrace();
}
try {
//Convert string to Double
bet = Double.parseDouble(input);
if(bet > user.getMoney()) {
System.out.println("You do not have enough money");
} else if(user.setBet(bet)) {
break;
} else {
System.out.println("Enter a bet greater than $2");
}
} catch (NumberFormatException stringInput) {
System.out.println("Enter a valid number");
}
}
}
//Deal cards
dealCards();
//Initial display
display();
//Ask for insurance if necessary
manageInsurance();
//Force players with naturals to stand
manageNaturals();
//Manage players who double down or split
for(User user: users) {
//Manage split pairs
if(user.getCard(0).getValue().equals(
user.getCard(1).getValue()) &&
user.getMoney() >= user.getBet()) {
System.out.println("----------");
displayPlayer(user);
if(choice("Do you want to split your pair?")) {
user.splitPair();
for(SplitPair pair: user.getSplitPairs()) {
pair.hit(deckPop());
}
}
}
//Manage doubledowns
if(user.getScore() >= 9 && user.getScore() <= 11 &&
user.getMoney() >= user.getBet()) {
System.out.println("----------");
displayPlayer(user);
if(choice("Do you want to double down?")) {
user.doubledown(deckPop());
}
}
}
finishDeal();
//Display Dealer's cards
System.out.println("\n----------\nDealer:");
for(Card card: getCards()) {
System.out.print(card.getFace() + " ");
}
System.out.println("\nScore: " + getScore());
//Start handing out money
//Insurance
if(getCard(0).isAce() && getScore() == 21) {
for(User user: users) {
user.finishInsurance();
}
}
for(User user: users) {
//Split pairs
if(user.isSplit()) {
for(SplitPair pair: user.getSplitPairs()) {
//Split pairs with an ace as their first card
// do not get 1.5X their bet from a blacjack
if(getScore() > 21) {
if(pair.getCard(0).isAce() &&
pair.getScore() == 21) {
pair.recieveReward(pair.getBet() * 2);
} else if(pair.hasNatural()) {
pair.recieveReward(pair.getBet() * 2.5);
} else if(pair.getScore() <= 21) {
pair.recieveReward(pair.getBet() * 2);
} else {
pair.recieveReward(0);
}
} else if(pair.getScore() < getScore()
|| pair.getScore() > 21) {
pair.recieveReward(0);
} else if (pair.getScore() == getScore()) {
pair.recieveReward(pair.getBet());
} else if(pair.getCard(0).isAce() &&
pair.getScore() == 21) {
pair.recieveReward(pair.getBet() * 2);
} else if(pair.hasNatural()) {
pair.recieveReward(pair.getBet() * 2.5);
} else {
pair.recieveReward(pair.getBet() * 2);
}
displaySplit(pair);
discardPile.addCards(pair.hand.removeAll());
}
user.getSplitPairs().clear();
displayPlayer(user);
user.stand = false;
} else {
//Users who have not split
if(getScore() > 21) {
if(user.hasNatural()) {
user.recieveReward(user.getBet() * 2.5);
} else if(user.getScore() <= 21) {
user.recieveReward(user.getBet() * 2);
} else {
user.recieveReward(0);
}
} else if(user.getScore() < getScore()
|| user.getScore() > 21) {
user.recieveReward(0);
} else if (user.getScore() == getScore()) {
user.recieveReward(user.getBet());
} else if(user.hasNatural()) {
user.recieveReward(user.getBet() * 2.5);
} else {
user.recieveReward(user.getBet() * 2);
}
displayPlayer(user);
discardPile.addCards(user.hand.removeAll());
user.stand = false;
}
}
discardPile.addCards(hand.removeAll());
}
private boolean choice(String question) {
//Ask the player a question. Return true if the answer is yes
System.out.println(question);
String input = "";
try {
//Get user input
input = reader.readLine();
} catch (IOException noInput) {
noInput.printStackTrace();
}
return input.toUpperCase().equals("YES") ||
input.toUpperCase().equals("Y");
}
private boolean hitOrStand() {
//Ask the player if they want to hit or stand
String input = "";
while(true) {
System.out.println("Will you hit or stand?");
try {
//Get user input
input = reader.readLine();
} catch (IOException noInput) {
noInput.printStackTrace();
}
if(input.toUpperCase().equals("HIT")) {
return true;
} else if(input.toUpperCase().equals("STAND")) {
return false;
}
}
}
private void displaySplit(SplitPair pair) {
//Print the data from the inputted split pair
System.out.println("\n" + pair.playerName + ":");
for(Card card: pair.getCards()) {
System.out.print(card.getFace() + " ");
}
System.out.println("\nScore: " + pair.getScore() +
"\nBet: $" + pair.getBet());
}
private void displayPlayer(User user) {
//Print the data from the inputted user
if(user.isSplit()) {
for(SplitPair pair: user.getSplitPairs()) {
displaySplit(pair);
}
} else {
System.out.println("\n" + user.playerName + ":");
for(Card card: user.getCards()) {
System.out.print(card.getFace() + " ");
}
System.out.println("\nScore: " + user.getScore() +
"\nMoney: $" + user.getMoney() + "\nBet: $" +
user.getBet() + "\nInsurance: $" +
user.getInsurance());
}
}
private void display() {
//Display the data from all players
System.out.println("\n----------\nDealer:\n" +
getCard(0).getFace() + " " +
getCard(1).getBack());
for(User user: users) {
displayPlayer(user);
}
}
private void dealCards() {
//Deal two cards to each player
for(int deal = 0; deal < 2; deal++) {
hand.add(deckPop());
for(User user: users) {
user.hit(deckPop());
}
}
}
private Card deckPop() {
//Checks if the next card is a blank and pops a card
if(deck.nextIsBlank()) {
deck.pop();
deck.refill(discardPile);
}
return deck.pop();
}
private void finishDeal() {
//Ask each player if they would like to hit until they all stand
for(User user: users) {
//Deal to split pairs
if(user.isSplit()) {
for(SplitPair split: user.getSplitPairs()) {
while(!split.stand) {
System.out.println("----------");
displaySplit(split);
if(hitOrStand()) {
split.hit(deckPop());
if(split.stand && !split.getCard(0).isAce()) {
displaySplit(split);
System.out.println("You have gone bust");
}
} else {
split.stand();
}
}
}
}
while(!user.stand) {
System.out.println("----------");
displayPlayer(user);
if(hitOrStand()) {
user.hit(deckPop());
if(user.stand) {
displayPlayer(user);
System.out.println("You have gone bust");
}
} else {
user.stand();
}
}
}
//Force the dealer to hit until they have a score of 17+
while(getScore() < 17) {
hand.add(deckPop());
}
}
private void manageNaturals() {
//Force the player to stand if he has a natural
for(User user: users) {
if(user.hasNatural()) {
System.out.println("----------\n" + user.playerName
+ " has 21");
user.stand();
}
}
}
private void manageInsurance() {
//Manage any players who wich to put down insurance
if(getCard(0).isAce()) {
for(User user: users) {
if(user.getMoney() >= user.getBet() / 2) {
System.out.println("----------");
displayPlayer(user);
if(choice("Do you want to put down insurance?")) {
user.addInsurance();
}
}
}
}
}
public static void main(String[] args) {
//Instantiate a dealer and start the game
Dealer dealer = new Dealer();
dealer.startGame();
}
} | 10,467 | 0.559034 | 0.551971 | 407 | 23.746929 | 18.13212 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.528255 | false | false | 9 |
9a731b7b566238ca79183a5de17dceb516b9ab4a | 26,087,631,382,960 | 54d82df8c4a69660f68fcf577e579369941822dc | /mfx-micro-service-server/mfx-micro-service-server-systemmgr/src/main/java/com/mfx/micro/service/provider/systemmgr/entity/RoleDO.java | 1dacba2e19878679a4997708be5e549754b97fa0 | [
"MIT"
] | permissive | v5zhu/mfx-micro-service | https://github.com/v5zhu/mfx-micro-service | 9ba5a3229e89f97dc078cfd7cf41670cc3915456 | 053b2ccaeac584bc559f90fa178107335866005b | refs/heads/master | 2020-03-08T04:52:44.397000 | 2018-06-20T01:27:43 | 2018-06-20T01:27:43 | 127,933,379 | 1 | 0 | MIT | false | 2020-07-01T18:07:14 | 2018-04-03T16:00:29 | 2020-06-05T08:26:01 | 2020-07-01T18:07:14 | 614 | 1 | 0 | 1 | Java | false | false | package com.mfx.micro.service.provider.systemmgr.entity;
import com.mfx.micro.service.component.common.base.entity.AbstractEntity;
import lombok.Getter;
import lombok.Setter;
import java.util.List;
@Getter
@Setter
public class RoleDO extends AbstractEntity {
private String name;
private Integer sort;
private String description;
// 格式id-permission
private List<String> permissions;
}
| UTF-8 | Java | 415 | java | RoleDO.java | Java | [] | null | [] | package com.mfx.micro.service.provider.systemmgr.entity;
import com.mfx.micro.service.component.common.base.entity.AbstractEntity;
import lombok.Getter;
import lombok.Setter;
import java.util.List;
@Getter
@Setter
public class RoleDO extends AbstractEntity {
private String name;
private Integer sort;
private String description;
// 格式id-permission
private List<String> permissions;
}
| 415 | 0.768856 | 0.768856 | 20 | 19.549999 | 20.294025 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.45 | false | false | 9 |
858bc5f5c48fd3284c65763dd7f51ce24164f329 | 26,087,631,382,580 | 633c56b194f71bb1840d55aeaa67590ad466151b | /src/main/java/com/zlp/auto_repair_system/service/PartsService.java | 6e3718464faa7d37198f96c32be862808b45a352 | [] | no_license | zlp-github/auto_repair_system1.1 | https://github.com/zlp-github/auto_repair_system1.1 | bf9cb22e11124232036db80c0b542fd9b294e0cc | 56f2a60c5fe8c5b1c514a645887edfb0c98bbaf2 | refs/heads/master | 2022-06-23T21:41:37.454000 | 2020-02-23T04:08:42 | 2020-02-23T04:08:42 | 239,508,336 | 0 | 0 | null | false | 2022-06-17T02:55:48 | 2020-02-10T12:38:07 | 2020-02-23T04:11:06 | 2022-06-17T02:55:48 | 104 | 0 | 0 | 1 | Java | false | false | package com.zlp.auto_repair_system.service;
import com.zlp.auto_repair_system.pojo.Parts;
import com.zlp.auto_repair_system.response.GetAllPartResponse;
import java.util.List;
/**
* Author: zlp
* Date: 2020-01-29 19:30
* Description:张立朋,写点注释吧!!
*/
public interface PartsService {
Integer addParts(Parts parts);
Integer addPartsList(List<Parts> partsList);
Parts findPartsById(Integer id);
List<Parts> findPartsByName(String name);
GetAllPartResponse getAllParts(Integer pageNumber, Integer pageSize);
Integer updateParts(Parts parts);
Integer updatePartsList(List<Parts> partsList);
Integer deleteParts(Integer id);
Integer deletePartsList(List<Integer> ids);
}
| UTF-8 | Java | 733 | java | PartsService.java | Java | [
{
"context": "tResponse;\n\nimport java.util.List;\n\n/**\n * Author: zlp\n * Date: 2020-01-29 19:30\n * Description:张立朋,写点注释",
"end": 198,
"score": 0.9996762275695801,
"start": 195,
"tag": "USERNAME",
"value": "zlp"
}
] | null | [] | package com.zlp.auto_repair_system.service;
import com.zlp.auto_repair_system.pojo.Parts;
import com.zlp.auto_repair_system.response.GetAllPartResponse;
import java.util.List;
/**
* Author: zlp
* Date: 2020-01-29 19:30
* Description:张立朋,写点注释吧!!
*/
public interface PartsService {
Integer addParts(Parts parts);
Integer addPartsList(List<Parts> partsList);
Parts findPartsById(Integer id);
List<Parts> findPartsByName(String name);
GetAllPartResponse getAllParts(Integer pageNumber, Integer pageSize);
Integer updateParts(Parts parts);
Integer updatePartsList(List<Parts> partsList);
Integer deleteParts(Integer id);
Integer deletePartsList(List<Integer> ids);
}
| 733 | 0.742657 | 0.725874 | 33 | 20.666666 | 22.135487 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.424242 | false | false | 9 |
ae582c7d616138e4ea3476c2f087fa93e7a34e94 | 21,457,656,667,127 | 2dddc5f0f280e27875f726c4801fca6f191484a2 | /src/main/java/com/wqb/appium/axpmathod/Login.java | 7d4f538c071793d083ce67684e08bf2690daeced | [] | no_license | wGodlike/wqbAppiumForAandroid | https://github.com/wGodlike/wqbAppiumForAandroid | 2f3eff9ef7ced0ce663531fc532668038ff5f842 | de3e8f1dfb9c473b663522363ed0d7fc62e8c5ef | refs/heads/master | 2020-03-17T09:41:36.444000 | 2018-06-07T02:52:05 | 2018-06-07T02:52:05 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.wqb.appium.axpmathod;
import com.wqb.appium.axppages.LoginPage;
import com.wqb.appium.capabilities.MyAndroidDriver;
import io.appium.java_client.android.AndroidDriver;
/**
* Created by wangqingbin on 2018/6/6.
*
*/
public class Login {
private String username = "appium";
private String pwd = "a11111";
public void login(AndroidDriver driver) throws InterruptedException {
LoginPage loginPage = new LoginPage(driver);
// 获取页面元素 并操作元素
loginPage.stuLogin();
loginPage.usernameid.sendKeys(username);
loginPage.password.sendKeys(pwd);
loginPage.savepwd.click();
if (loginPage.savepwd.getAttribute("checked").equals("true")){
System.out.println("记住密码已勾选成功");
}else {
System.out.println("记住密码已勾选失败");
}
loginPage.loginbtn.click();
}
}
| UTF-8 | Java | 931 | java | Login.java | Java | [
{
"context": "a_client.android.AndroidDriver;\n\n/**\n * Created by wangqingbin on 2018/6/6.\n *\n */\npublic class Login {\n\n pri",
"end": 211,
"score": 0.9997220039367676,
"start": 200,
"tag": "USERNAME",
"value": "wangqingbin"
},
{
"context": "lic class Login {\n\n private String username = \"appium\";\n private String pwd = \"a11111\";\n\n public ",
"end": 291,
"score": 0.9993793964385986,
"start": 285,
"tag": "USERNAME",
"value": "appium"
},
{
"context": "ng username = \"appium\";\n private String pwd = \"a11111\";\n\n public void login(AndroidDriver driver) th",
"end": 326,
"score": 0.9993080496788025,
"start": 320,
"tag": "PASSWORD",
"value": "a11111"
},
{
"context": "ys(username);\n loginPage.password.sendKeys(pwd);\n\n loginPage.savepwd.click();\n if ",
"end": 602,
"score": 0.9365301132202148,
"start": 599,
"tag": "PASSWORD",
"value": "pwd"
}
] | null | [] | package com.wqb.appium.axpmathod;
import com.wqb.appium.axppages.LoginPage;
import com.wqb.appium.capabilities.MyAndroidDriver;
import io.appium.java_client.android.AndroidDriver;
/**
* Created by wangqingbin on 2018/6/6.
*
*/
public class Login {
private String username = "appium";
private String pwd = "<PASSWORD>";
public void login(AndroidDriver driver) throws InterruptedException {
LoginPage loginPage = new LoginPage(driver);
// 获取页面元素 并操作元素
loginPage.stuLogin();
loginPage.usernameid.sendKeys(username);
loginPage.password.sendKeys(pwd);
loginPage.savepwd.click();
if (loginPage.savepwd.getAttribute("checked").equals("true")){
System.out.println("记住密码已勾选成功");
}else {
System.out.println("记住密码已勾选失败");
}
loginPage.loginbtn.click();
}
}
| 935 | 0.659794 | 0.647194 | 35 | 23.942858 | 22.247879 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false | 9 |
4b5e080bd1c38db26c165bb57057cf3ccb6ed382 | 22,840,636,126,227 | a697acaceb71bb07aa73e6957732785d167c0644 | /src/com/uslc/pe/jpa/test/UslcJpaManager.java | 1b8b11fa75bb7adbfc3c32a1a809a023a3c9c335 | [] | no_license | betoche/uslc_pe_jpa | https://github.com/betoche/uslc_pe_jpa | 3646dd908c8a1099fb830679123d2627c495c70d | a31d5c43eff25dc6a31e1a573ba587821caacdc3 | refs/heads/master | 2021-01-25T00:10:34.278000 | 2015-06-30T05:48:09 | 2015-06-30T05:48:09 | 38,290,260 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.uslc.pe.jpa.test;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.Query;
import static org.eclipse.persistence.config.PersistenceUnitProperties.*;
import javax.persistence.spi.PersistenceUnitTransactionType;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.eclipse.persistence.config.TargetServer;
import com.uslc.pe.jpa.comparator.ColorComparator;
import com.uslc.pe.jpa.entity.Color;
import com.uslc.pe.jpa.entity.Style;
import com.uslc.pe.jpa.entity.PurchaseOrder;
import com.uslc.pe.jpa.entity.PurchaseOrderDetail;
import com.uslc.pe.jpa.entity.Size;
import com.uslc.pe.jpa.entity.Upc;
import com.uslc.pe.jpa.entity.User;
import com.uslc.pe.jpa.logic.UserType;
import com.uslc.pe.jpa.util.Encryptor;
import com.uslc.pe.jpa.util.UslcJpa;
public class UslcJpaManager {
public List<PurchaseOrder> poList = null;
private Map<String,String> properties = null;
public List<Color> colorList = null;
public List<Upc> upcList = null;
public List<Style> itemList = null;
public List<Size> sizeList = null;
public List<User> userList = null;
private UslcJpa jpa = null;
private static Logger log = null;
public UslcJpaManager( String dbHost, int dbPort, String dbName, String dbUser, String dbPassword, String jdbcDriver ) {
properties = new HashMap<String, String>();
// Ensure RESOURCE_LOCAL transactions is used.
properties.put(TRANSACTION_TYPE, PersistenceUnitTransactionType.RESOURCE_LOCAL.name());
// Configure the internal EclipseLink connection pool
properties.put(JDBC_DRIVER, jdbcDriver);
properties.put(JDBC_URL, "jdbc:mysql://"+dbHost+":"+dbPort+"/" + dbName);
properties.put(JDBC_USER, dbUser);
properties.put(JDBC_PASSWORD, dbPassword);
// Configure logging. FINE ensures all SQL is shown
properties.put(LOGGING_LEVEL, "FINE");
properties.put(LOGGING_TIMESTAMP, "false");
properties.put(LOGGING_THREAD, "false");
properties.put(LOGGING_SESSION, "false");
// Ensure that no server-platform is configured
properties.put(TARGET_SERVER, TargetServer.None);
}
public List<PurchaseOrder> getPurchaseOrderList() {
if( poList == null ) {
Query q = getJpa().getEntityManager().createQuery("SELECT po FROM PurchaseOrder po WHERE po.deleted=:deleted ORDER BY po.referenceNumber DESC");
q.setParameter("deleted", false);
//q.setHint("javax.persistence.cache.storeMode", "REFRESH");
poList = (List<PurchaseOrder>)q.getResultList();
/*for( PurchaseOrder po : poList ) {
getJpa().refresh( po );
}*/
}
return poList;
}
public List<Color> getColors(){
if( colorList == null ) {
Query q = getJpa().getEntityManager().createQuery("SELECT c FROM Color c");
colorList = (List<Color>)q.getResultList();
}
return colorList;
}
public List<Upc> getUpcs(){
if( upcList == null ) {
Query q = getJpa().getEntityManager().createQuery("SELECT u FROM Upc u ORDER BY u.deleted, u.upcCode ASC");
upcList = (List<Upc>)q.getResultList();
}
return upcList;
}
public List<Style> getItems() {
if( itemList == null ) {
Query q = getJpa().getEntityManager().createQuery("SELECT i FROM Item i");
itemList = (List<Style>)q.getResultList();
}
return itemList;
}
public List<Size> getSizes() {
if( sizeList == null ) {
Query q = getJpa().getEntityManager().createQuery("SELECT s FROM Size s");
sizeList = (List<Size>)q.getResultList();
}
return sizeList;
}
public List<User> getUsers() {
if( userList == null ) {
Query q = getJpa().getEntityManager().createQuery("SELECT u FROM User u ORDER BY u.enabled DESC, u.userType ASC, u.firstName ASC");
userList = (List<User>)q.getResultList();
getLog().info( "userList size: " + userList.size() );
if( userList==null || !(userList.size()>0) ) {
User user = new User();
user.setId(-1);
user.setUsername( "Admin" );
user.setPassword( "QtoGVZsBx8F+qyZTWR4b0w==" );
user.setFirstName("admin");
user.setLastName("uslc");
user.setEnabled(true);
user.setActive(false);
user.setUserType(UserType.ADMIN.getId());
user.setTimestamp( Calendar.getInstance().getTime() );
userList = new ArrayList<User>();
userList.add(user);
}
}
return userList;
}
public User[] getUsers(boolean enabled) {
User[] users = new User[0];
List<User> userList = new ArrayList<User>();
for( User u : getUsers() ) {
if( u.isEnabled()==enabled ) {
userList.add(u);
}
}
users = userList.toArray(users);
return users;
}
public void refreshUsers() {
for(User u : getUsers()) {
getJpa().refresh( u );
}
}
public UslcJpa getJpa() {
if( jpa == null ) {
jpa = new UslcJpa( getProperties() );
}
return jpa;
}
public PurchaseOrderDetail[] getPurchaseOrderDetails( PurchaseOrder po, boolean deleted ) {
PurchaseOrderDetail[] pods = new PurchaseOrderDetail[0];
List<PurchaseOrderDetail> podList = new ArrayList<PurchaseOrderDetail>();
for( PurchaseOrderDetail pod : po.getPurchaseOrderDetails() ) {
if( pod.getDeleted()==deleted ) {
podList.add(pod);
}
}
pods = podList.toArray(pods);
return pods;
}
public PurchaseOrderDetail[] getPurchaseOrderDetails( PurchaseOrder po, Color color, boolean deleted ){
PurchaseOrderDetail[] pods = new PurchaseOrderDetail[0];
List<PurchaseOrderDetail> podList = new ArrayList<PurchaseOrderDetail>();
for( PurchaseOrderDetail pod : po.getPurchaseOrderDetails() ) {
if( pod.getDeleted()==deleted ) {
Upc upc = pod.getUpc();
if( upc.getColor().getId() == color.getId() ) {
podList.add(pod);
}
}
}
pods = podList.toArray(pods);
return pods;
}
public Color[] getColors( PurchaseOrder po, boolean deleted ) {
Color[] colors = new Color[0];
List<Color> colorList = new ArrayList<Color>();
for( PurchaseOrderDetail pod : getPurchaseOrderDetails(po, deleted) ) {
Upc upc = pod.getUpc();
boolean exists = false;
for( Color c : colorList ) {
if( c.getId() == upc.getColor().getId() ) {
exists = true;
}
}
if( !exists ) {
colorList.add( upc.getColor() );
}
}
Collections.sort(colorList, new ColorComparator() );
colors = colorList.toArray(colors);
return colors;
}
public User getUser( String username, String password ) {
User user = null;
Encryptor enc = new Encryptor("");
for( User u : getUsers() ) {
getLog().info( "encripted pass: " + enc.encrypt(password) + " against " + u.getPassword() );
if( u.getUsername()!=null && u.getPassword()!=null && u.getUsername().compareTo( username )==0 && u.getPassword().compareTo( enc.encrypt(password) )==0 ) {
user = u;
break;
}
}
return user;
}
private Map<String,String> getProperties(){
return properties;
}
public void updateLiveDataAccess() {
getJpa().evictAll();
poList = null;
colorList = null;
upcList = null;
itemList = null;
sizeList = null;
userList = null;
}
public static void main(String[] args) {
}
public User[] getUsersClients(boolean enabled) {
User[] users = new User[0];
List<User> userList = new ArrayList<User>();
for( User u : getUsers() ) {
if( u.isEnabled()==enabled && u.getUserType()==1 ) {
userList.add(u);
}
}
users = userList.toArray(users);
return users;
}
private static Logger getLog() {
if( log == null ) {
log = Logger.getLogger(UslcJpaManager.class);
PropertyConfigurator.configure( "log4j.properties" );
}
return log;
}
}
| UTF-8 | Java | 7,968 | java | UslcJpaManager.java | Java | [
{
"context": "USER, dbUser);\r\n\t properties.put(JDBC_PASSWORD, dbPassword);\r\n\t \r\n\t // Configure logging. FINE ensures al",
"end": 1958,
"score": 0.7745593190193176,
"start": 1948,
"tag": "PASSWORD",
"value": "dbPassword"
},
{
"context": "r();\r\n\t\t\t\tuser.setId(-1);\r\n\t\t\t\tuser.setUsername( \"Admin\" );\r\n\t\t\t\tuser.setPassword( \"QtoGVZsBx8F+qyZTWR4b0",
"end": 4167,
"score": 0.9979331493377686,
"start": 4162,
"tag": "USERNAME",
"value": "Admin"
},
{
"context": "r.setUsername( \"Admin\" );\r\n\t\t\t\tuser.setPassword( \"QtoGVZsBx8F+qyZTWR4b0w==\" );\r\n\t\t\t\tuser.setFirstName(\"admin\");\r\n\t\t\t\tuser.set",
"end": 4218,
"score": 0.9994192123413086,
"start": 4196,
"tag": "PASSWORD",
"value": "QtoGVZsBx8F+qyZTWR4b0w"
}
] | null | [] | package com.uslc.pe.jpa.test;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.Query;
import static org.eclipse.persistence.config.PersistenceUnitProperties.*;
import javax.persistence.spi.PersistenceUnitTransactionType;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.eclipse.persistence.config.TargetServer;
import com.uslc.pe.jpa.comparator.ColorComparator;
import com.uslc.pe.jpa.entity.Color;
import com.uslc.pe.jpa.entity.Style;
import com.uslc.pe.jpa.entity.PurchaseOrder;
import com.uslc.pe.jpa.entity.PurchaseOrderDetail;
import com.uslc.pe.jpa.entity.Size;
import com.uslc.pe.jpa.entity.Upc;
import com.uslc.pe.jpa.entity.User;
import com.uslc.pe.jpa.logic.UserType;
import com.uslc.pe.jpa.util.Encryptor;
import com.uslc.pe.jpa.util.UslcJpa;
public class UslcJpaManager {
public List<PurchaseOrder> poList = null;
private Map<String,String> properties = null;
public List<Color> colorList = null;
public List<Upc> upcList = null;
public List<Style> itemList = null;
public List<Size> sizeList = null;
public List<User> userList = null;
private UslcJpa jpa = null;
private static Logger log = null;
public UslcJpaManager( String dbHost, int dbPort, String dbName, String dbUser, String dbPassword, String jdbcDriver ) {
properties = new HashMap<String, String>();
// Ensure RESOURCE_LOCAL transactions is used.
properties.put(TRANSACTION_TYPE, PersistenceUnitTransactionType.RESOURCE_LOCAL.name());
// Configure the internal EclipseLink connection pool
properties.put(JDBC_DRIVER, jdbcDriver);
properties.put(JDBC_URL, "jdbc:mysql://"+dbHost+":"+dbPort+"/" + dbName);
properties.put(JDBC_USER, dbUser);
properties.put(JDBC_PASSWORD, <PASSWORD>);
// Configure logging. FINE ensures all SQL is shown
properties.put(LOGGING_LEVEL, "FINE");
properties.put(LOGGING_TIMESTAMP, "false");
properties.put(LOGGING_THREAD, "false");
properties.put(LOGGING_SESSION, "false");
// Ensure that no server-platform is configured
properties.put(TARGET_SERVER, TargetServer.None);
}
public List<PurchaseOrder> getPurchaseOrderList() {
if( poList == null ) {
Query q = getJpa().getEntityManager().createQuery("SELECT po FROM PurchaseOrder po WHERE po.deleted=:deleted ORDER BY po.referenceNumber DESC");
q.setParameter("deleted", false);
//q.setHint("javax.persistence.cache.storeMode", "REFRESH");
poList = (List<PurchaseOrder>)q.getResultList();
/*for( PurchaseOrder po : poList ) {
getJpa().refresh( po );
}*/
}
return poList;
}
public List<Color> getColors(){
if( colorList == null ) {
Query q = getJpa().getEntityManager().createQuery("SELECT c FROM Color c");
colorList = (List<Color>)q.getResultList();
}
return colorList;
}
public List<Upc> getUpcs(){
if( upcList == null ) {
Query q = getJpa().getEntityManager().createQuery("SELECT u FROM Upc u ORDER BY u.deleted, u.upcCode ASC");
upcList = (List<Upc>)q.getResultList();
}
return upcList;
}
public List<Style> getItems() {
if( itemList == null ) {
Query q = getJpa().getEntityManager().createQuery("SELECT i FROM Item i");
itemList = (List<Style>)q.getResultList();
}
return itemList;
}
public List<Size> getSizes() {
if( sizeList == null ) {
Query q = getJpa().getEntityManager().createQuery("SELECT s FROM Size s");
sizeList = (List<Size>)q.getResultList();
}
return sizeList;
}
public List<User> getUsers() {
if( userList == null ) {
Query q = getJpa().getEntityManager().createQuery("SELECT u FROM User u ORDER BY u.enabled DESC, u.userType ASC, u.firstName ASC");
userList = (List<User>)q.getResultList();
getLog().info( "userList size: " + userList.size() );
if( userList==null || !(userList.size()>0) ) {
User user = new User();
user.setId(-1);
user.setUsername( "Admin" );
user.setPassword( "<PASSWORD>==" );
user.setFirstName("admin");
user.setLastName("uslc");
user.setEnabled(true);
user.setActive(false);
user.setUserType(UserType.ADMIN.getId());
user.setTimestamp( Calendar.getInstance().getTime() );
userList = new ArrayList<User>();
userList.add(user);
}
}
return userList;
}
public User[] getUsers(boolean enabled) {
User[] users = new User[0];
List<User> userList = new ArrayList<User>();
for( User u : getUsers() ) {
if( u.isEnabled()==enabled ) {
userList.add(u);
}
}
users = userList.toArray(users);
return users;
}
public void refreshUsers() {
for(User u : getUsers()) {
getJpa().refresh( u );
}
}
public UslcJpa getJpa() {
if( jpa == null ) {
jpa = new UslcJpa( getProperties() );
}
return jpa;
}
public PurchaseOrderDetail[] getPurchaseOrderDetails( PurchaseOrder po, boolean deleted ) {
PurchaseOrderDetail[] pods = new PurchaseOrderDetail[0];
List<PurchaseOrderDetail> podList = new ArrayList<PurchaseOrderDetail>();
for( PurchaseOrderDetail pod : po.getPurchaseOrderDetails() ) {
if( pod.getDeleted()==deleted ) {
podList.add(pod);
}
}
pods = podList.toArray(pods);
return pods;
}
public PurchaseOrderDetail[] getPurchaseOrderDetails( PurchaseOrder po, Color color, boolean deleted ){
PurchaseOrderDetail[] pods = new PurchaseOrderDetail[0];
List<PurchaseOrderDetail> podList = new ArrayList<PurchaseOrderDetail>();
for( PurchaseOrderDetail pod : po.getPurchaseOrderDetails() ) {
if( pod.getDeleted()==deleted ) {
Upc upc = pod.getUpc();
if( upc.getColor().getId() == color.getId() ) {
podList.add(pod);
}
}
}
pods = podList.toArray(pods);
return pods;
}
public Color[] getColors( PurchaseOrder po, boolean deleted ) {
Color[] colors = new Color[0];
List<Color> colorList = new ArrayList<Color>();
for( PurchaseOrderDetail pod : getPurchaseOrderDetails(po, deleted) ) {
Upc upc = pod.getUpc();
boolean exists = false;
for( Color c : colorList ) {
if( c.getId() == upc.getColor().getId() ) {
exists = true;
}
}
if( !exists ) {
colorList.add( upc.getColor() );
}
}
Collections.sort(colorList, new ColorComparator() );
colors = colorList.toArray(colors);
return colors;
}
public User getUser( String username, String password ) {
User user = null;
Encryptor enc = new Encryptor("");
for( User u : getUsers() ) {
getLog().info( "encripted pass: " + enc.encrypt(password) + " against " + u.getPassword() );
if( u.getUsername()!=null && u.getPassword()!=null && u.getUsername().compareTo( username )==0 && u.getPassword().compareTo( enc.encrypt(password) )==0 ) {
user = u;
break;
}
}
return user;
}
private Map<String,String> getProperties(){
return properties;
}
public void updateLiveDataAccess() {
getJpa().evictAll();
poList = null;
colorList = null;
upcList = null;
itemList = null;
sizeList = null;
userList = null;
}
public static void main(String[] args) {
}
public User[] getUsersClients(boolean enabled) {
User[] users = new User[0];
List<User> userList = new ArrayList<User>();
for( User u : getUsers() ) {
if( u.isEnabled()==enabled && u.getUserType()==1 ) {
userList.add(u);
}
}
users = userList.toArray(users);
return users;
}
private static Logger getLog() {
if( log == null ) {
log = Logger.getLogger(UslcJpaManager.class);
PropertyConfigurator.configure( "log4j.properties" );
}
return log;
}
}
| 7,956 | 0.651355 | 0.649347 | 282 | 26.25532 | 26.542326 | 158 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.336879 | false | false | 9 |
718a65e943d27fcd0d12c533b19f4bfa40d686f9 | 22,840,636,126,918 | 961016a614c6785e6fe8f6bfd7214676f0d91064 | /Portlets/ProgateServiceBuilder-portlet/docroot/WEB-INF/service/larion/progate/model/OrganizationViewClp.java | 2cc288bdbf6622328fb96ae92f91063265943b70 | [] | no_license | thaond/progate-lmis | https://github.com/thaond/progate-lmis | f58c447c58c11217e2247c7ca3349a44ad7f3bbd | d143b7e7d56a22cc9ce6256ca6fb77a11459e6d6 | refs/heads/master | 2021-01-10T03:00:26.888000 | 2011-07-28T14:12:54 | 2011-07-28T14:12:54 | 44,992,742 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* Copyright (c) 2000-2009 Liferay, Inc. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package larion.progate.model;
import com.liferay.portal.kernel.bean.ReadOnlyBeanHandler;
import com.liferay.portal.kernel.util.HtmlUtil;
import com.liferay.portal.model.impl.BaseModelImpl;
import java.io.Serializable;
import java.lang.reflect.Proxy;
/**
* <a href="OrganizationViewClp.java.html"><b><i>View Source</i></b></a>
*
* @author Brian Wing Shun Chan
*
*/
public class OrganizationViewClp extends BaseModelImpl<OrganizationView>
implements OrganizationView {
public OrganizationViewClp() {
}
public int getPrimaryKey() {
return _orgId;
}
public void setPrimaryKey(int pk) {
setOrgId(pk);
}
public Serializable getPrimaryKeyObj() {
return new Integer(_orgId);
}
public int getOrgId() {
return _orgId;
}
public void setOrgId(int orgId) {
_orgId = orgId;
}
public String getOrgName() {
return _orgName;
}
public void setOrgName(String orgName) {
_orgName = orgName;
}
public int getCountProduct() {
return _countProduct;
}
public void setCountProduct(int countProduct) {
_countProduct = countProduct;
}
public String getOrgNameLower() {
return _orgNameLower;
}
public void setOrgNameLower(String orgNameLower) {
_orgNameLower = orgNameLower;
}
public OrganizationView toEscapedModel() {
if (isEscapedModel()) {
return this;
}
else {
OrganizationView model = new OrganizationViewClp();
model.setEscapedModel(true);
model.setOrgId(getOrgId());
model.setOrgName(HtmlUtil.escape(getOrgName()));
model.setCountProduct(getCountProduct());
model.setOrgNameLower(HtmlUtil.escape(getOrgNameLower()));
model = (OrganizationView)Proxy.newProxyInstance(OrganizationView.class.getClassLoader(),
new Class[] { OrganizationView.class },
new ReadOnlyBeanHandler(model));
return model;
}
}
public Object clone() {
OrganizationViewClp clone = new OrganizationViewClp();
clone.setOrgId(getOrgId());
clone.setOrgName(getOrgName());
clone.setCountProduct(getCountProduct());
clone.setOrgNameLower(getOrgNameLower());
return clone;
}
public int compareTo(OrganizationView organizationView) {
int value = 0;
if (getCountProduct() < organizationView.getCountProduct()) {
value = -1;
}
else if (getCountProduct() > organizationView.getCountProduct()) {
value = 1;
}
else {
value = 0;
}
value = value * -1;
if (value != 0) {
return value;
}
value = getOrgName().compareTo(organizationView.getOrgName());
if (value != 0) {
return value;
}
return 0;
}
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
OrganizationViewClp organizationView = null;
try {
organizationView = (OrganizationViewClp)obj;
}
catch (ClassCastException cce) {
return false;
}
int pk = organizationView.getPrimaryKey();
if (getPrimaryKey() == pk) {
return true;
}
else {
return false;
}
}
public int hashCode() {
return getPrimaryKey();
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{orgId=");
sb.append(getOrgId());
sb.append(", orgName=");
sb.append(getOrgName());
sb.append(", countProduct=");
sb.append(getCountProduct());
sb.append(", orgNameLower=");
sb.append(getOrgNameLower());
sb.append("}");
return sb.toString();
}
public String toXmlString() {
StringBuilder sb = new StringBuilder();
sb.append("<model><model-name>");
sb.append("larion.progate.model.OrganizationView");
sb.append("</model-name>");
sb.append(
"<column><column-name>orgId</column-name><column-value><![CDATA[");
sb.append(getOrgId());
sb.append("]]></column-value></column>");
sb.append(
"<column><column-name>orgName</column-name><column-value><![CDATA[");
sb.append(getOrgName());
sb.append("]]></column-value></column>");
sb.append(
"<column><column-name>countProduct</column-name><column-value><![CDATA[");
sb.append(getCountProduct());
sb.append("]]></column-value></column>");
sb.append(
"<column><column-name>orgNameLower</column-name><column-value><![CDATA[");
sb.append(getOrgNameLower());
sb.append("]]></column-value></column>");
sb.append("</model>");
return sb.toString();
}
private int _orgId;
private String _orgName;
private int _countProduct;
private String _orgNameLower;
} | UTF-8 | Java | 5,445 | java | OrganizationViewClp.java | Java | [
{
"context": ".html\"><b><i>View Source</i></b></a>\n *\n * @author Brian Wing Shun Chan\n *\n */\npublic class OrganizationViewClp extends B",
"end": 1511,
"score": 0.9473559260368347,
"start": 1491,
"tag": "NAME",
"value": "Brian Wing Shun Chan"
}
] | null | [] | /**
* Copyright (c) 2000-2009 Liferay, Inc. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package larion.progate.model;
import com.liferay.portal.kernel.bean.ReadOnlyBeanHandler;
import com.liferay.portal.kernel.util.HtmlUtil;
import com.liferay.portal.model.impl.BaseModelImpl;
import java.io.Serializable;
import java.lang.reflect.Proxy;
/**
* <a href="OrganizationViewClp.java.html"><b><i>View Source</i></b></a>
*
* @author <NAME>
*
*/
public class OrganizationViewClp extends BaseModelImpl<OrganizationView>
implements OrganizationView {
public OrganizationViewClp() {
}
public int getPrimaryKey() {
return _orgId;
}
public void setPrimaryKey(int pk) {
setOrgId(pk);
}
public Serializable getPrimaryKeyObj() {
return new Integer(_orgId);
}
public int getOrgId() {
return _orgId;
}
public void setOrgId(int orgId) {
_orgId = orgId;
}
public String getOrgName() {
return _orgName;
}
public void setOrgName(String orgName) {
_orgName = orgName;
}
public int getCountProduct() {
return _countProduct;
}
public void setCountProduct(int countProduct) {
_countProduct = countProduct;
}
public String getOrgNameLower() {
return _orgNameLower;
}
public void setOrgNameLower(String orgNameLower) {
_orgNameLower = orgNameLower;
}
public OrganizationView toEscapedModel() {
if (isEscapedModel()) {
return this;
}
else {
OrganizationView model = new OrganizationViewClp();
model.setEscapedModel(true);
model.setOrgId(getOrgId());
model.setOrgName(HtmlUtil.escape(getOrgName()));
model.setCountProduct(getCountProduct());
model.setOrgNameLower(HtmlUtil.escape(getOrgNameLower()));
model = (OrganizationView)Proxy.newProxyInstance(OrganizationView.class.getClassLoader(),
new Class[] { OrganizationView.class },
new ReadOnlyBeanHandler(model));
return model;
}
}
public Object clone() {
OrganizationViewClp clone = new OrganizationViewClp();
clone.setOrgId(getOrgId());
clone.setOrgName(getOrgName());
clone.setCountProduct(getCountProduct());
clone.setOrgNameLower(getOrgNameLower());
return clone;
}
public int compareTo(OrganizationView organizationView) {
int value = 0;
if (getCountProduct() < organizationView.getCountProduct()) {
value = -1;
}
else if (getCountProduct() > organizationView.getCountProduct()) {
value = 1;
}
else {
value = 0;
}
value = value * -1;
if (value != 0) {
return value;
}
value = getOrgName().compareTo(organizationView.getOrgName());
if (value != 0) {
return value;
}
return 0;
}
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
OrganizationViewClp organizationView = null;
try {
organizationView = (OrganizationViewClp)obj;
}
catch (ClassCastException cce) {
return false;
}
int pk = organizationView.getPrimaryKey();
if (getPrimaryKey() == pk) {
return true;
}
else {
return false;
}
}
public int hashCode() {
return getPrimaryKey();
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{orgId=");
sb.append(getOrgId());
sb.append(", orgName=");
sb.append(getOrgName());
sb.append(", countProduct=");
sb.append(getCountProduct());
sb.append(", orgNameLower=");
sb.append(getOrgNameLower());
sb.append("}");
return sb.toString();
}
public String toXmlString() {
StringBuilder sb = new StringBuilder();
sb.append("<model><model-name>");
sb.append("larion.progate.model.OrganizationView");
sb.append("</model-name>");
sb.append(
"<column><column-name>orgId</column-name><column-value><![CDATA[");
sb.append(getOrgId());
sb.append("]]></column-value></column>");
sb.append(
"<column><column-name>orgName</column-name><column-value><![CDATA[");
sb.append(getOrgName());
sb.append("]]></column-value></column>");
sb.append(
"<column><column-name>countProduct</column-name><column-value><![CDATA[");
sb.append(getCountProduct());
sb.append("]]></column-value></column>");
sb.append(
"<column><column-name>orgNameLower</column-name><column-value><![CDATA[");
sb.append(getOrgNameLower());
sb.append("]]></column-value></column>");
sb.append("</model>");
return sb.toString();
}
private int _orgId;
private String _orgName;
private int _countProduct;
private String _orgNameLower;
} | 5,431 | 0.701194 | 0.698255 | 226 | 23.097345 | 23.833109 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.707965 | false | false | 9 |
f791feb409edeff6367601b538260bb36f2a7bcf | 11,596,411,703,739 | 87488addcb957c458ccdab37958fa6dd2cfa3568 | /zhongtie/business/src/main/java/com/digital/dl2/business/net/obj/NetBorrowingBookData.java | 0ad16ad65ce3ef93c78304f0487f223af2fdf31b | [] | no_license | qilai616man/zhongtie | https://github.com/qilai616man/zhongtie | 952999415ff011b4bdc8e95cd783a8f17ea0b2ca | ed83a6ae0cf5e8e71a6e75e6fd853fd6134ead4b | refs/heads/master | 2020-05-24T09:26:12.712000 | 2019-05-17T12:10:41 | 2019-05-17T12:10:41 | 187,203,274 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.digital.dl2.business.net.obj;
/**
* Created by qinqi on 15/11/24.
*/
public class NetBorrowingBookData {
private int goods_id;
private String thumb;
private String title;
private String author;
private String description;
private long borrow_time;
private String download_url;
@Override
public String toString() {
return "NetBorrowingBookData{" +
"goods_id=" + goods_id +
", thumb='" + thumb + '\'' +
", title='" + title + '\'' +
", author='" + author + '\'' +
", description='" + description + '\'' +
", borrow_time=" + borrow_time +
", download_url='" + download_url + '\'' +
'}';
}
public int getGoods_id() {
return goods_id;
}
public void setGoods_id(int goods_id) {
this.goods_id = goods_id;
}
public String getThumb() {
return thumb;
}
public void setThumb(String thumb) {
this.thumb = thumb;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public long getBorrow_time() {
return borrow_time;
}
public void setBorrow_time(long borrow_time) {
this.borrow_time = borrow_time;
}
public String getDownload_url() {
return download_url;
}
public void setDownload_url(String download_url) {
this.download_url = download_url;
}
}
| UTF-8 | Java | 1,859 | java | NetBorrowingBookData.java | Java | [
{
"context": "m.digital.dl2.business.net.obj;\n\n/**\n * Created by qinqi on 15/11/24.\n */\npublic class NetBorrowingBookDat",
"end": 66,
"score": 0.9993836283683777,
"start": 61,
"tag": "USERNAME",
"value": "qinqi"
}
] | null | [] | package com.digital.dl2.business.net.obj;
/**
* Created by qinqi on 15/11/24.
*/
public class NetBorrowingBookData {
private int goods_id;
private String thumb;
private String title;
private String author;
private String description;
private long borrow_time;
private String download_url;
@Override
public String toString() {
return "NetBorrowingBookData{" +
"goods_id=" + goods_id +
", thumb='" + thumb + '\'' +
", title='" + title + '\'' +
", author='" + author + '\'' +
", description='" + description + '\'' +
", borrow_time=" + borrow_time +
", download_url='" + download_url + '\'' +
'}';
}
public int getGoods_id() {
return goods_id;
}
public void setGoods_id(int goods_id) {
this.goods_id = goods_id;
}
public String getThumb() {
return thumb;
}
public void setThumb(String thumb) {
this.thumb = thumb;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public long getBorrow_time() {
return borrow_time;
}
public void setBorrow_time(long borrow_time) {
this.borrow_time = borrow_time;
}
public String getDownload_url() {
return download_url;
}
public void setDownload_url(String download_url) {
this.download_url = download_url;
}
}
| 1,859 | 0.548682 | 0.544917 | 83 | 21.397591 | 17.654612 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.349398 | false | false | 9 |
e1f43c5550c85b9ceca55543afcf0eceb0a74465 | 10,368,051,094,430 | 4de10c14848f023bd2a3b43d1543c70a299fccd9 | /model-basic/src/main/java/com/forcam/na/ffwebservices/model/AbstractResponse.java | c267e3275bdac4c0591c1287d2986ba713ec3bd6 | [
"MIT"
] | permissive | FORCAM-FORCE-Bridge-API/java-sdk | https://github.com/FORCAM-FORCE-Bridge-API/java-sdk | 682cead62552be170b35a95f8ae7b809c41835a4 | d694e45f7759ddfae38a5f1ba958c576a39ecc46 | refs/heads/master | 2023-01-22T22:21:36.718000 | 2020-11-20T10:00:28 | 2020-11-20T10:00:28 | 312,293,612 | 0 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.forcam.na.ffwebservices.model;
/**
* The abstract super class for models.
*/
public class AbstractResponse {
// ------------------------------------------------------------------------
// members
// ------------------------------------------------------------------------
/** A link to itself. */
private LinkEmbeddedWSModel<Object> mSelf;
// ------------------------------------------------------------------------
// getters/setters
// ------------------------------------------------------------------------
public LinkEmbeddedWSModel getSelf() {
return mSelf;
}
@SuppressWarnings("unchecked")
public void setSelf(LinkEmbeddedWSModel self) {
this.mSelf = self;
}
} | UTF-8 | Java | 755 | java | AbstractResponse.java | Java | [] | null | [] | package com.forcam.na.ffwebservices.model;
/**
* The abstract super class for models.
*/
public class AbstractResponse {
// ------------------------------------------------------------------------
// members
// ------------------------------------------------------------------------
/** A link to itself. */
private LinkEmbeddedWSModel<Object> mSelf;
// ------------------------------------------------------------------------
// getters/setters
// ------------------------------------------------------------------------
public LinkEmbeddedWSModel getSelf() {
return mSelf;
}
@SuppressWarnings("unchecked")
public void setSelf(LinkEmbeddedWSModel self) {
this.mSelf = self;
}
} | 755 | 0.377483 | 0.377483 | 27 | 27 | 27.089701 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.148148 | false | false | 9 |
667a706d5fbbee8c48da6e06a54d1dd5dd252e3f | 11,845,519,836,436 | dd84da501f2c8d5587bf4a8a5afc8b67af578a78 | /src/test/java/gov/nci/ppe/services/CodeServiceTest.java | 158ab8dde4bfc8b063f656143c2a28ef031c483e | [] | no_license | CBIIT/ncippe-application | https://github.com/CBIIT/ncippe-application | d17a5b29f878107e11ee60a73ddacc3e151004b0 | 8ea05c393204b0e00eac9295ad5a86de6fec930f | refs/heads/develop | 2023-08-09T08:32:21.320000 | 2023-07-31T16:28:56 | 2023-07-31T16:28:56 | 218,971,485 | 2 | 0 | null | false | 2023-06-30T10:25:29 | 2019-11-01T11:18:43 | 2023-02-02T08:41:03 | 2023-06-30T10:24:57 | 589 | 2 | 0 | 0 | Java | false | false | package gov.nci.ppe.services;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.springframework.test.context.ActiveProfiles;
import gov.nci.ppe.data.entity.Code;
import gov.nci.ppe.data.repository.CodeRepository;
import gov.nci.ppe.services.impl.CodeServiceImpl;
@ActiveProfiles("unittest")
@Tag("service")
@DisplayName("Unit Tests for CodeServiceImpl class")
public class CodeServiceTest {
@InjectMocks
private CodeServiceImpl codeService;
@Mock
private CodeRepository mockCodeRepo;
@BeforeEach
public void initMocks() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testGetCode() {
String input = "input";
Code expected = new Code();
expected.setCodeName(input);
Mockito.when(mockCodeRepo.findByCodeName(input)).thenReturn(expected);
Code actual = codeService.getCode(input);
assertNotNull(actual);
assertEquals(expected, actual);
Mockito.verify(mockCodeRepo).findByCodeName(input);
}
}
| UTF-8 | Java | 1,299 | java | CodeServiceTest.java | Java | [] | null | [] | package gov.nci.ppe.services;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.springframework.test.context.ActiveProfiles;
import gov.nci.ppe.data.entity.Code;
import gov.nci.ppe.data.repository.CodeRepository;
import gov.nci.ppe.services.impl.CodeServiceImpl;
@ActiveProfiles("unittest")
@Tag("service")
@DisplayName("Unit Tests for CodeServiceImpl class")
public class CodeServiceTest {
@InjectMocks
private CodeServiceImpl codeService;
@Mock
private CodeRepository mockCodeRepo;
@BeforeEach
public void initMocks() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testGetCode() {
String input = "input";
Code expected = new Code();
expected.setCodeName(input);
Mockito.when(mockCodeRepo.findByCodeName(input)).thenReturn(expected);
Code actual = codeService.getCode(input);
assertNotNull(actual);
assertEquals(expected, actual);
Mockito.verify(mockCodeRepo).findByCodeName(input);
}
}
| 1,299 | 0.791378 | 0.791378 | 51 | 24.470589 | 20.035608 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.078431 | false | false | 9 |
6f6da8c7bc2d2d2e4a99d59351c21b1a779f05a8 | 25,245,817,810,217 | 1d6bfe21a951806ef3fd6984fefaf2b66f44b66a | /com/comverse/udt/udtrequest/BillFmtOptFormatsUpdateRequest.java | d29fa121c9add8350633d1f8869eed4310615fe2 | [] | no_license | patrickmcgrory/Projects | https://github.com/patrickmcgrory/Projects | 218e1c3ea4f3f57f5f6f218889eb289d927f639e | 6a9024efc9cb968df3f5cbd3b5cb8cd5482095d8 | refs/heads/master | 2018-04-22T06:02:19.798000 | 2015-11-14T17:30:16 | 2015-11-14T17:30:16 | 91,143,423 | 0 | 0 | null | true | 2017-05-13T02:19:23 | 2017-05-13T02:19:23 | 2015-11-02T14:45:23 | 2015-11-14T17:30:51 | 9,760 | 0 | 0 | 0 | null | null | null | /**----------------------------------------------------------------------------+
* Copyright 2006 by Comverse, Inc. |
* All Rights Reserved |
*-----------------------------------------------------------------------------+
*
* Filename
* ========
* BillFmtOptFormatsUpdateRequest.java
*
* DO NOT EDIT. THIS IS AN AUTOMATICALLY GENERATED FILE.
*-----------------------------------------------------------------------------*/
package com.comverse.udt.udtrequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.math.BigInteger;
import com.csgsystems.api.bulk.*;
import com.csgsystems.udt.*;
import com.csgsystems.cf.data.*;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
*
* Class used to create a BillFmtOptFormatsUpdateRequest Udt Request
*
*/
public class BillFmtOptFormatsUpdateRequest extends BillFmtOptFormatsSubRequestParent {
/**
*
* Constructor to create a BillFmtOptFormatsUpdateRequest
* @param id Unique request name
* @param BillFmtOptFormatsUpdateIn BillFmtOptFormatsObjectData for BillFmtOptFormatsUpdateRequest
*
*/
@JsonCreator
public BillFmtOptFormatsUpdateRequest(@JsonProperty("RequestId") String id, @JsonProperty("BillFmtOptFormats")BillFmtOptFormatsObjectData BillFmtOptFormatsUpdateIn) {
super(id, "BillFmtOptFormatsUpdate");
if (BillFmtOptFormatsUpdateIn != null) {
addInput("BillFmtOptFormats", BillFmtOptFormatsObjectHelper.toMap(BillFmtOptFormatsUpdateIn, new HashMap(), "BillFmtOptFormats").get("BillFmtOptFormats"));
}
}
/**
*
* Retrieves the BillFmtOptFormatsObjectData that results from the BillFmtOptFormatsUpdateRequest call
* @return BillFmtOptFormatsObjectData resulting from udt call
*
*/
public BillFmtOptFormatsObjectData getOutput() {
return BillFmtOptFormatsObjectHelper.fromMap(outputMap, "BillFmtOptFormats");
}
}
| UTF-8 | Java | 2,016 | java | BillFmtOptFormatsUpdateRequest.java | Java | [] | null | [] | /**----------------------------------------------------------------------------+
* Copyright 2006 by Comverse, Inc. |
* All Rights Reserved |
*-----------------------------------------------------------------------------+
*
* Filename
* ========
* BillFmtOptFormatsUpdateRequest.java
*
* DO NOT EDIT. THIS IS AN AUTOMATICALLY GENERATED FILE.
*-----------------------------------------------------------------------------*/
package com.comverse.udt.udtrequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.math.BigInteger;
import com.csgsystems.api.bulk.*;
import com.csgsystems.udt.*;
import com.csgsystems.cf.data.*;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
*
* Class used to create a BillFmtOptFormatsUpdateRequest Udt Request
*
*/
public class BillFmtOptFormatsUpdateRequest extends BillFmtOptFormatsSubRequestParent {
/**
*
* Constructor to create a BillFmtOptFormatsUpdateRequest
* @param id Unique request name
* @param BillFmtOptFormatsUpdateIn BillFmtOptFormatsObjectData for BillFmtOptFormatsUpdateRequest
*
*/
@JsonCreator
public BillFmtOptFormatsUpdateRequest(@JsonProperty("RequestId") String id, @JsonProperty("BillFmtOptFormats")BillFmtOptFormatsObjectData BillFmtOptFormatsUpdateIn) {
super(id, "BillFmtOptFormatsUpdate");
if (BillFmtOptFormatsUpdateIn != null) {
addInput("BillFmtOptFormats", BillFmtOptFormatsObjectHelper.toMap(BillFmtOptFormatsUpdateIn, new HashMap(), "BillFmtOptFormats").get("BillFmtOptFormats"));
}
}
/**
*
* Retrieves the BillFmtOptFormatsObjectData that results from the BillFmtOptFormatsUpdateRequest call
* @return BillFmtOptFormatsObjectData resulting from udt call
*
*/
public BillFmtOptFormatsObjectData getOutput() {
return BillFmtOptFormatsObjectHelper.fromMap(outputMap, "BillFmtOptFormats");
}
}
| 2,016 | 0.650298 | 0.648313 | 59 | 33.169491 | 39.41098 | 168 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.372881 | false | false | 9 |
2fd6fb27dc365ef1875d211e2d8a4f083c349e77 | 14,276,471,310,414 | cf596777c54bb9bfaae56e112b22e1d6d1f6cc70 | /src/com/cdqidi/bb/user/UserExtProfile.java | 9df6e5178818bedd3d17f95dc1fe122cba464472 | [] | no_license | DHonly123/bbtimes_manage | https://github.com/DHonly123/bbtimes_manage | e55d7df2dd288ad7ef3c038ea160ba73cbfbf508 | 1e98d4574659a44d5fc053639f4ab57760d09230 | refs/heads/master | 2021-05-19T19:37:49.271000 | 2014-11-19T04:21:01 | 2014-11-19T04:21:01 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.cdqidi.bb.user;
import com.jfinal.ext.plugin.tablebind.TableBind;
import com.jfinal.plugin.activerecord.Model;
@TableBind(tableName="be_extprofiles",pkName="extProfileID")
public class UserExtProfile extends Model<UserExtProfile> {
private static final long serialVersionUID = 1L;
public final static UserExtProfile dao = new UserExtProfile();
}
| UTF-8 | Java | 372 | java | UserExtProfile.java | Java | [] | null | [] | package com.cdqidi.bb.user;
import com.jfinal.ext.plugin.tablebind.TableBind;
import com.jfinal.plugin.activerecord.Model;
@TableBind(tableName="be_extprofiles",pkName="extProfileID")
public class UserExtProfile extends Model<UserExtProfile> {
private static final long serialVersionUID = 1L;
public final static UserExtProfile dao = new UserExtProfile();
}
| 372 | 0.787634 | 0.784946 | 10 | 35.200001 | 24.75399 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.8 | false | false | 9 |
ff6f878d5f264b2f692472b9f3657e05292845f3 | 14,276,471,314,192 | eb53a910752cbaffeac992c1adbf2342a5c33f15 | /uti-0.0.1-SNAPSHOT/src/main/java/com/olol/model/gen/handler/Variable.java | f579d3b8a3131d5f0bed0ade68b4a7c75e3cb25e | [] | no_license | yangshuan/pepo | https://github.com/yangshuan/pepo | 23cefa2ba3e3135a13fea4da111bdb1cffb5c061 | a7f263e668f0db26a67c0ef85b1f1f6b954c8386 | refs/heads/master | 2020-05-30T05:12:57.267000 | 2013-08-12T00:18:58 | 2013-08-12T00:18:58 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.olol.model.gen.handler;
public class Variable {
public String name;
public String output;
public Boolean source;
public String norm;
public String params;
}
| UTF-8 | Java | 189 | java | Variable.java | Java | [] | null | [] | package com.olol.model.gen.handler;
public class Variable {
public String name;
public String output;
public Boolean source;
public String norm;
public String params;
}
| 189 | 0.714286 | 0.714286 | 11 | 15.181818 | 11.745933 | 35 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.090909 | false | false | 9 |
dffc4c4f5af37191b0bbcd5e95a9d50e20dfc7f4 | 34,514,357,240,600 | 5d04b911dc4054dfa9faf44af953dcdaa2455aa0 | /contract/src/test/java/org/semanticweb/owlapi/api/test/ontology/MissingDeclarationRoundTripTestCase.java | ab6cc5d71635d2c57b27859a9f1e6d0241e8d2ef | [] | no_license | RadW2020/owl-api | https://github.com/RadW2020/owl-api | 1c17877f72b64aafcb55f51f848d4c6cb5971130 | a4214d0cd3eead93225874e440e8c604a39a4a46 | refs/heads/master | 2021-01-18T16:43:21.362000 | 2017-03-31T21:16:23 | 2017-03-31T21:16:23 | 86,758,992 | 0 | 0 | null | true | 2017-03-30T23:43:41 | 2017-03-30T23:43:41 | 2017-02-06T04:21:12 | 2013-02-03T17:30:03 | 47,692 | 0 | 0 | 0 | null | null | null | package org.semanticweb.owlapi.api.test.ontology;
import static org.junit.Assert.*;
import static org.semanticweb.owlapi.apibinding.OWLFunctionalSyntaxFactory.*;
import org.junit.Before;
import org.junit.Test;
import org.semanticweb.owlapi.api.test.Factory;
import org.semanticweb.owlapi.io.RDFXMLOntologyFormat;
import org.semanticweb.owlapi.io.StringDocumentSource;
import org.semanticweb.owlapi.io.StringDocumentTarget;
import org.semanticweb.owlapi.model.OWLAnnotationAssertionAxiom;
import org.semanticweb.owlapi.model.OWLAnnotationProperty;
import org.semanticweb.owlapi.model.OWLClass;
import org.semanticweb.owlapi.model.OWLOntology;
import org.semanticweb.owlapi.model.OWLOntologyCreationException;
import org.semanticweb.owlapi.model.OWLOntologyLoaderConfiguration;
import org.semanticweb.owlapi.model.OWLOntologyManager;
import org.semanticweb.owlapi.model.OWLOntologyStorageException;
/** Test for 3186250 */
@SuppressWarnings("javadoc")
public class MissingDeclarationRoundTripTestCase {
String NS;
OWLClass A;
OWLAnnotationProperty P;
@Before
public void setUp() {
NS = "http://test.org/MissingDeclaration.owl";
A = Class(IRI(NS + "#A"));
P = AnnotationProperty(IRI(NS + "#p"));
}
@Test
public void shouldFindOneAxiom() throws OWLOntologyCreationException,
OWLOntologyStorageException {
OWLOntology ontology = createOntology();
assertTrue(ontology.containsAnnotationPropertyInSignature(P.getIRI()));
assertEquals(1, ontology.getAxiomCount());
String saved = saveOntology(ontology);
ontology = loadOntology(saved);
assertTrue(ontology.containsAnnotationPropertyInSignature(P.getIRI()));
assertEquals(1, ontology.getAxiomCount());
}
private OWLOntology createOntology() throws OWLOntologyCreationException {
OWLOntologyManager manager = Factory.getManager();
OWLOntology ontology = manager.createOntology(IRI(NS));
OWLAnnotationAssertionAxiom axiom = AnnotationAssertion(P, A.getIRI(),
Literal("Hello"));
manager.addAxiom(ontology, axiom);
return ontology;
}
public String saveOntology(OWLOntology ontology) throws OWLOntologyStorageException {
StringDocumentTarget target = new StringDocumentTarget();
OWLOntologyManager manager = ontology.getOWLOntologyManager();
RDFXMLOntologyFormat format = new RDFXMLOntologyFormat();
format.setAddMissingTypes(false);
manager.saveOntology(ontology, format, target);
return target.toString();
}
public OWLOntology loadOntology(String o) throws OWLOntologyCreationException {
OWLOntologyManager manager = Factory.getManager();
OWLOntologyLoaderConfiguration config = new OWLOntologyLoaderConfiguration();
config.setStrict(true);
return manager.loadOntologyFromOntologyDocument(new StringDocumentSource(o),
config);
}
}
| UTF-8 | Java | 2,981 | java | MissingDeclarationRoundTripTestCase.java | Java | [] | null | [] | package org.semanticweb.owlapi.api.test.ontology;
import static org.junit.Assert.*;
import static org.semanticweb.owlapi.apibinding.OWLFunctionalSyntaxFactory.*;
import org.junit.Before;
import org.junit.Test;
import org.semanticweb.owlapi.api.test.Factory;
import org.semanticweb.owlapi.io.RDFXMLOntologyFormat;
import org.semanticweb.owlapi.io.StringDocumentSource;
import org.semanticweb.owlapi.io.StringDocumentTarget;
import org.semanticweb.owlapi.model.OWLAnnotationAssertionAxiom;
import org.semanticweb.owlapi.model.OWLAnnotationProperty;
import org.semanticweb.owlapi.model.OWLClass;
import org.semanticweb.owlapi.model.OWLOntology;
import org.semanticweb.owlapi.model.OWLOntologyCreationException;
import org.semanticweb.owlapi.model.OWLOntologyLoaderConfiguration;
import org.semanticweb.owlapi.model.OWLOntologyManager;
import org.semanticweb.owlapi.model.OWLOntologyStorageException;
/** Test for 3186250 */
@SuppressWarnings("javadoc")
public class MissingDeclarationRoundTripTestCase {
String NS;
OWLClass A;
OWLAnnotationProperty P;
@Before
public void setUp() {
NS = "http://test.org/MissingDeclaration.owl";
A = Class(IRI(NS + "#A"));
P = AnnotationProperty(IRI(NS + "#p"));
}
@Test
public void shouldFindOneAxiom() throws OWLOntologyCreationException,
OWLOntologyStorageException {
OWLOntology ontology = createOntology();
assertTrue(ontology.containsAnnotationPropertyInSignature(P.getIRI()));
assertEquals(1, ontology.getAxiomCount());
String saved = saveOntology(ontology);
ontology = loadOntology(saved);
assertTrue(ontology.containsAnnotationPropertyInSignature(P.getIRI()));
assertEquals(1, ontology.getAxiomCount());
}
private OWLOntology createOntology() throws OWLOntologyCreationException {
OWLOntologyManager manager = Factory.getManager();
OWLOntology ontology = manager.createOntology(IRI(NS));
OWLAnnotationAssertionAxiom axiom = AnnotationAssertion(P, A.getIRI(),
Literal("Hello"));
manager.addAxiom(ontology, axiom);
return ontology;
}
public String saveOntology(OWLOntology ontology) throws OWLOntologyStorageException {
StringDocumentTarget target = new StringDocumentTarget();
OWLOntologyManager manager = ontology.getOWLOntologyManager();
RDFXMLOntologyFormat format = new RDFXMLOntologyFormat();
format.setAddMissingTypes(false);
manager.saveOntology(ontology, format, target);
return target.toString();
}
public OWLOntology loadOntology(String o) throws OWLOntologyCreationException {
OWLOntologyManager manager = Factory.getManager();
OWLOntologyLoaderConfiguration config = new OWLOntologyLoaderConfiguration();
config.setStrict(true);
return manager.loadOntologyFromOntologyDocument(new StringDocumentSource(o),
config);
}
}
| 2,981 | 0.745052 | 0.742033 | 72 | 40.402779 | 26.443682 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.75 | false | false | 9 |
7cff01526985f52f04a17271aa66aa70091d11d0 | 39,041,252,759,935 | fbb17914f39d4ad9c6cb1d9e84d9ab5a71a9d7a5 | /C83-S3-Pzm-SpringBoot/src/main/java/com/yc/C83S3PzmSpringBoot/dao/UserDao.java | 7103645f22818fcf5362e19e918af93f6529bca6 | [] | no_license | kerm11/C83 | https://github.com/kerm11/C83 | 3b5526dae9dd41e8c2c1c95f2cbe21008d2c0ef6 | c9719423a3b2d91a121492b8ab83125b10b38082 | refs/heads/master | 2022-12-31T18:27:18.807000 | 2020-10-22T12:18:15 | 2020-10-22T12:18:15 | 287,691,355 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.yc.C83S3PzmSpringBoot.dao;
import org.springframework.stereotype.Repository;
/**
* 由张三负责开发UserDao
*/
import com.yc.damai.po.DmUser;
@Repository
public class UserDao {
/**
* 该方法还未完成
* @param name
* @param pwd
* @return
*/
public DmUser selectByLogin(String name,String pwd) {
//张三完成了模块开发
//return new DmUser();
return null;
}
}
| UTF-8 | Java | 430 | java | UserDao.java | Java | [] | null | [] | package com.yc.C83S3PzmSpringBoot.dao;
import org.springframework.stereotype.Repository;
/**
* 由张三负责开发UserDao
*/
import com.yc.damai.po.DmUser;
@Repository
public class UserDao {
/**
* 该方法还未完成
* @param name
* @param pwd
* @return
*/
public DmUser selectByLogin(String name,String pwd) {
//张三完成了模块开发
//return new DmUser();
return null;
}
}
| 430 | 0.653646 | 0.645833 | 22 | 15.454545 | 15.014318 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.909091 | false | false | 9 |
dba91dbe08c932c9c829cae1c00bfe59713b7778 | 38,620,345,951,857 | 77b2dfeec8e504da2039bf11edfc4d9f3484348c | /src/org/sgpro/util/log/AbsLogOutput.java | 41a3a32d63408a3dd6418fb95c3ec2d0ade130ae | [] | no_license | lujx1024/robotServer | https://github.com/lujx1024/robotServer | a653775e62dae56477c9466ac6244fb6dd4baae1 | 34e231250861c1c7f74aae82b8560ff981e9d6ab | refs/heads/master | 2020-03-22T23:40:28.256000 | 2018-07-13T08:59:18 | 2018-07-13T08:59:18 | 140,822,860 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.sgpro.util.log;
import java.util.HashSet;
import java.util.Set;
import org.apache.log4j.Logger;
import org.sgpro.util.ExceptionUtil;
import config.Log4jInit;
public abstract class AbsLogOutput implements LogOutput {
static Logger logger = Logger.getLogger(AbsLogOutput.class.getName());
public AbsLogOutput() {
// TODO Auto-generated constructor stub
}
public abstract void customLog(String tag, String position, String message, Throwable t) ;
private long bitset =
LOG_LEVEL.ERROR.level()
| LOG_LEVEL.DEBUG.level()
| LOG_LEVEL.INFOR.level()
| LOG_LEVEL.WARN.level();
/**
* 不输出 commonLog 自己产生的log,否则陷入死递归
*/
public void commonLog(String levelName, StringBuilder sender, int position, Throwable t, String format, Object...args) {
try {
String stackTrace = ExceptionUtil.getExcetpionTrace(t);
String strPosition = ExceptionUtil.dumapStackTrace(Thread.currentThread().getStackTrace()[position]);
String tag = sender == null? strPosition : sender.toString();
String DONT_SAVE_OWNER_LOG = this.getClass().getName() + "." + "commonLog";
if (stackTrace != null && stackTrace.contains(DONT_SAVE_OWNER_LOG)) {
throw new Exception("Dead recusive....");
}
String message = String.format(format, args);
message = String.format("(%s) %s", Thread.currentThread().getName(), message) ;
if (isLogOn(LOG_LEVEL.parse(levelName))) {
systemLog(levelName, tag, message, t);
customLog(tag, strPosition, message, t);
}
} catch (Exception e) {
// TODO Auto-generated catch block
// System.err.println("AbsWOTPLogOutput", "Fata error", e);
logger.error(e.getMessage());
}
}
protected abstract void systemLog(String levelName, String tag, String message, Throwable t) ;
// with postion and sender.
public void err(StringBuilder sender, int position, String format, Object...args) {
commonLog("e", sender, position, null, format, args);
}
public void err(StringBuilder sender, int position, Throwable t, String format, Object...args) {
commonLog("e", sender, position, t, format, args);
}
public void debug(StringBuilder sender, int position, String format, Object...args) {
commonLog("d", sender, position, null, format, args);
}
public void warn(StringBuilder sender, int position, String format, Object...args) {
commonLog("w", sender, position, null, format, args);
}
public void info(StringBuilder sender, int position, String format, Object...args) {
commonLog("i", sender, position, null, format, args);
}
// with sender no position
// use default position.
public void err(StringBuilder sender, String format, Object...args) {
err(sender, 5, format, args);
}
public void err(StringBuilder sender, Throwable t, String format, Object...args) {
err(sender, 5, t, format, args);
}
public void debug(StringBuilder sender, String format, Object...args) {
debug(sender, 5, format, args);
}
public void warn(StringBuilder sender, String format, Object...args) {
warn(sender, 5, format, args);
}
public void info(StringBuilder sender, String format, Object...args) {
info(sender, 5, format, args);
}
// no sender with position
// use default sender.
public void err(int position, String format, Object...args) {
err(senderName, position, format, args);
}
public void err(int position, Throwable t, String format, Object...args) {
err(senderName, position, t, format, args);
}
public void debug(int position, String format, Object...args) {
debug(senderName, position, format, args);
}
public void warn(int position, String format, Object...args) {
warn(senderName, position, format, args);
}
public void info(int position, String format, Object...args) {
info(senderName, position, format, args);
}
// no sender no position.
// default position.
// default sender.
public void err(String format, Object...args) {
err(senderName, 5, format, args);
}
public void err(Throwable t, String format, Object...args) {
err(senderName, 5, t, format, args);
}
public void debug(String format, Object...args) {
debug(senderName, 5, format, args);
}
public void warn(String format, Object...args) {
warn(senderName, 5, format, args);
}
public void info(String format, Object...args) {
info(senderName, 5, format, args);
}
@Override
public void setLogOn(LOG_LEVEL level, boolean value) {
// TODO Auto-generated method stub
if (level != null) {
bitset = value? (bitset | level.level()) : (bitset & ~level.level());
}
}
@Override
public boolean isLogOn(LOG_LEVEL level) {
// TODO Auto-generated method stub
return level == null? false : (bitset & level.level()) != 0;
}
@Override
public Set<LOG_LEVEL> logOnSet() {
// TODO Auto-generated method stub
Set<LOG_LEVEL> ret = new HashSet<LogOutput.LOG_LEVEL>();
for (LOG_LEVEL l : LOG_LEVEL.values()) {
if (isLogOn(l)) {
ret.add(l);
}
}
return ret;
}
private StringBuilder senderName = null;
//
@Override
public void setDefaultSenderName(StringBuilder senderName) {
// TODO Auto-generated method stub
this.senderName = senderName;
}
}
| UTF-8 | Java | 5,396 | java | AbsLogOutput.java | Java | [
{
"context": " Auto-generated method stub\r\n\t\tthis.senderName = senderName;\r\n\t}\r\n}\r\n",
"end": 5350,
"score": 0.6977847218513489,
"start": 5344,
"tag": "NAME",
"value": "sender"
}
] | null | [] | package org.sgpro.util.log;
import java.util.HashSet;
import java.util.Set;
import org.apache.log4j.Logger;
import org.sgpro.util.ExceptionUtil;
import config.Log4jInit;
public abstract class AbsLogOutput implements LogOutput {
static Logger logger = Logger.getLogger(AbsLogOutput.class.getName());
public AbsLogOutput() {
// TODO Auto-generated constructor stub
}
public abstract void customLog(String tag, String position, String message, Throwable t) ;
private long bitset =
LOG_LEVEL.ERROR.level()
| LOG_LEVEL.DEBUG.level()
| LOG_LEVEL.INFOR.level()
| LOG_LEVEL.WARN.level();
/**
* 不输出 commonLog 自己产生的log,否则陷入死递归
*/
public void commonLog(String levelName, StringBuilder sender, int position, Throwable t, String format, Object...args) {
try {
String stackTrace = ExceptionUtil.getExcetpionTrace(t);
String strPosition = ExceptionUtil.dumapStackTrace(Thread.currentThread().getStackTrace()[position]);
String tag = sender == null? strPosition : sender.toString();
String DONT_SAVE_OWNER_LOG = this.getClass().getName() + "." + "commonLog";
if (stackTrace != null && stackTrace.contains(DONT_SAVE_OWNER_LOG)) {
throw new Exception("Dead recusive....");
}
String message = String.format(format, args);
message = String.format("(%s) %s", Thread.currentThread().getName(), message) ;
if (isLogOn(LOG_LEVEL.parse(levelName))) {
systemLog(levelName, tag, message, t);
customLog(tag, strPosition, message, t);
}
} catch (Exception e) {
// TODO Auto-generated catch block
// System.err.println("AbsWOTPLogOutput", "Fata error", e);
logger.error(e.getMessage());
}
}
protected abstract void systemLog(String levelName, String tag, String message, Throwable t) ;
// with postion and sender.
public void err(StringBuilder sender, int position, String format, Object...args) {
commonLog("e", sender, position, null, format, args);
}
public void err(StringBuilder sender, int position, Throwable t, String format, Object...args) {
commonLog("e", sender, position, t, format, args);
}
public void debug(StringBuilder sender, int position, String format, Object...args) {
commonLog("d", sender, position, null, format, args);
}
public void warn(StringBuilder sender, int position, String format, Object...args) {
commonLog("w", sender, position, null, format, args);
}
public void info(StringBuilder sender, int position, String format, Object...args) {
commonLog("i", sender, position, null, format, args);
}
// with sender no position
// use default position.
public void err(StringBuilder sender, String format, Object...args) {
err(sender, 5, format, args);
}
public void err(StringBuilder sender, Throwable t, String format, Object...args) {
err(sender, 5, t, format, args);
}
public void debug(StringBuilder sender, String format, Object...args) {
debug(sender, 5, format, args);
}
public void warn(StringBuilder sender, String format, Object...args) {
warn(sender, 5, format, args);
}
public void info(StringBuilder sender, String format, Object...args) {
info(sender, 5, format, args);
}
// no sender with position
// use default sender.
public void err(int position, String format, Object...args) {
err(senderName, position, format, args);
}
public void err(int position, Throwable t, String format, Object...args) {
err(senderName, position, t, format, args);
}
public void debug(int position, String format, Object...args) {
debug(senderName, position, format, args);
}
public void warn(int position, String format, Object...args) {
warn(senderName, position, format, args);
}
public void info(int position, String format, Object...args) {
info(senderName, position, format, args);
}
// no sender no position.
// default position.
// default sender.
public void err(String format, Object...args) {
err(senderName, 5, format, args);
}
public void err(Throwable t, String format, Object...args) {
err(senderName, 5, t, format, args);
}
public void debug(String format, Object...args) {
debug(senderName, 5, format, args);
}
public void warn(String format, Object...args) {
warn(senderName, 5, format, args);
}
public void info(String format, Object...args) {
info(senderName, 5, format, args);
}
@Override
public void setLogOn(LOG_LEVEL level, boolean value) {
// TODO Auto-generated method stub
if (level != null) {
bitset = value? (bitset | level.level()) : (bitset & ~level.level());
}
}
@Override
public boolean isLogOn(LOG_LEVEL level) {
// TODO Auto-generated method stub
return level == null? false : (bitset & level.level()) != 0;
}
@Override
public Set<LOG_LEVEL> logOnSet() {
// TODO Auto-generated method stub
Set<LOG_LEVEL> ret = new HashSet<LogOutput.LOG_LEVEL>();
for (LOG_LEVEL l : LOG_LEVEL.values()) {
if (isLogOn(l)) {
ret.add(l);
}
}
return ret;
}
private StringBuilder senderName = null;
//
@Override
public void setDefaultSenderName(StringBuilder senderName) {
// TODO Auto-generated method stub
this.senderName = senderName;
}
}
| 5,396 | 0.663497 | 0.661074 | 185 | 26.994595 | 28.122608 | 121 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.486486 | false | false | 9 |
cf646ca86df9b5ee0ee8abf4b7829c5ef939fac8 | 39,024,072,868,083 | 445b80f3a965d79af362cf2b115721ad14ad3b27 | /com.cn55.program/src/cn55/model/SortPurchaseType.java | 185b8ad664bd9d8b4267de027de7f6e84c54c9c1 | [] | no_license | codeninja55/csit121-assignment02 | https://github.com/codeninja55/csit121-assignment02 | dea2fd6da2971ea2570ed3c81df70f57adbd3404 | bf51263760ec3d17f32e29b2e5fc82c45637b360 | refs/heads/master | 2021-06-30T01:06:55.511000 | 2017-09-12T08:25:50 | 2017-09-12T08:25:50 | 103,997,913 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn55.model;
public enum SortPurchaseType {
// Constants
All(1, "All Purchases"),
Card(2, "Purchases with Cards"),
Cash(3, "Purchases Cash")
;
// Instance Variables
private final int id;
private final String name;
SortPurchaseType(int id, String name) {
this.name = name;
this.id = id;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
} | UTF-8 | Java | 464 | java | SortPurchaseType.java | Java | [] | null | [] | package cn55.model;
public enum SortPurchaseType {
// Constants
All(1, "All Purchases"),
Card(2, "Purchases with Cards"),
Cash(3, "Purchases Cash")
;
// Instance Variables
private final int id;
private final String name;
SortPurchaseType(int id, String name) {
this.name = name;
this.id = id;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
} | 464 | 0.573276 | 0.5625 | 26 | 16.884615 | 12.908933 | 43 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.538462 | false | false | 9 |
4e8ba3ad88140de968f812faf238a48f3b0c380c | 34,772,055,277,345 | ca48e72d41db9edf7547a720160bfdfac85ba6ea | /src/main/java/seedu/whatsleft/logic/parser/DeleteCommandParser.java | 38dccccddf0935794ab28acc54517e89931e5cdc | [
"MIT"
] | permissive | CS2103JAN2017-W10-B4/main | https://github.com/CS2103JAN2017-W10-B4/main | 33a6f2a0afedac1c8c4c704cfd9660817c6f7802 | c8e964dd65801e126716a860a670a92d3e6ccf41 | refs/heads/master | 2021-01-20T15:31:09.369000 | 2017-04-09T17:16:24 | 2017-04-09T17:16:24 | 82,758,675 | 0 | 0 | null | true | 2017-04-09T12:18:12 | 2017-02-22T03:58:53 | 2017-03-05T04:53:05 | 2017-04-09T12:18:12 | 10,739 | 0 | 0 | 2 | Java | null | null | package seedu.whatsleft.logic.parser;
import static seedu.whatsleft.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import java.util.Optional;
import seedu.whatsleft.logic.commands.Command;
import seedu.whatsleft.logic.commands.DeleteCommand;
import seedu.whatsleft.logic.commands.IncorrectCommand;
/**
* Parses input arguments and creates a new DeleteCommand object
*/
public class DeleteCommandParser {
//@@author A0110491U
/**
* Parses the given {@code String} of arguments in the context of the DeleteCommand
* and returns an DeleteCommand object for execution.
*/
public Command parse(String args) {
Optional<Integer> index = ParserUtil.parseIndex(args);
if (!index.isPresent()) {
return new IncorrectCommand(
String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE));
}
Optional<String> type = ParserUtil.parseType(args);
if (!type.isPresent()) {
return new IncorrectCommand(
String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE));
}
if (!type.get().equalsIgnoreCase("ev") && !type.get().equalsIgnoreCase("ts")) {
return new IncorrectCommand(
String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE));
}
return new DeleteCommand(index.get(), type.get().toLowerCase());
}
}
| UTF-8 | Java | 1,451 | java | DeleteCommandParser.java | Java | [
{
"context": "\npublic class DeleteCommandParser {\n //@@author A0110491U\n /**\n * Parses the given {@code String} of",
"end": 441,
"score": 0.9990479350090027,
"start": 432,
"tag": "USERNAME",
"value": "A0110491U"
}
] | null | [] | package seedu.whatsleft.logic.parser;
import static seedu.whatsleft.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import java.util.Optional;
import seedu.whatsleft.logic.commands.Command;
import seedu.whatsleft.logic.commands.DeleteCommand;
import seedu.whatsleft.logic.commands.IncorrectCommand;
/**
* Parses input arguments and creates a new DeleteCommand object
*/
public class DeleteCommandParser {
//@@author A0110491U
/**
* Parses the given {@code String} of arguments in the context of the DeleteCommand
* and returns an DeleteCommand object for execution.
*/
public Command parse(String args) {
Optional<Integer> index = ParserUtil.parseIndex(args);
if (!index.isPresent()) {
return new IncorrectCommand(
String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE));
}
Optional<String> type = ParserUtil.parseType(args);
if (!type.isPresent()) {
return new IncorrectCommand(
String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE));
}
if (!type.get().equalsIgnoreCase("ev") && !type.get().equalsIgnoreCase("ts")) {
return new IncorrectCommand(
String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE));
}
return new DeleteCommand(index.get(), type.get().toLowerCase());
}
}
| 1,451 | 0.674018 | 0.669194 | 41 | 34.390244 | 31.807253 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.390244 | false | false | 9 |
37585cff82b77998a8330893937cb9f07e7f7e3d | 39,530,879,032,105 | cfda6b496bc8dc78e5d2279335be1b8da96eece3 | /libs/Qilin-61993c188700/src/qilin/primitives/generic/MerkleTree.java | 9679ce0aab381a53f9dca68f8cbc08c98adf1688 | [
"MIT"
] | permissive | adityasawhney/SmartMeterIQ | https://github.com/adityasawhney/SmartMeterIQ | 6c1cfe16dc52ef7c7c447d76df2e8b6aa90ac43c | 5486b0862bfc4dcab05e58026af62c4849c87272 | refs/heads/master | 2021-01-10T20:49:29.219000 | 2013-07-15T21:51:27 | 2013-07-15T21:51:27 | 11,434,617 | 2 | 3 | null | null | null | null | null | null | null | null | null | null | null | null | null | package qilin.primitives.generic;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import qilin.primitives.CollisionResistantHash;
import qilin.util.EncodingUtils;
import qilin.util.GenericsUtils;
import qilin.util.Pair;
import qilin.util.StreamEncoder;
/**
* Implmentation of a binary Merkle tree commitment using a generic collision-resistant hash.
* @author talm
*
* @param <C> The type determining the range and domain of the collision-resistant hash.
* The hash function must map a pair of elements of this type to a single element of
* this type.
*
* @see CollisionResistantHash
*/
public class MerkleTree<C> {
/**
* The hash function used to generate the Merkle tree.
*/
protected CollisionResistantHash<C, Pair<C, C>> hashfunc;
/**
* The root of the Merkle Tree.
*/
protected Node root;
/**
* The maximum length of a path from a leaf to the root.
*/
protected int depth;
/**
* A map from leaf hashvalues to the nodes that represent them.
*/
Map<C, Node> leafToNode;
/**
* A node in the Merkle tree. Each node has a value and pointers to its child nodes.
* The value is computed by hashing the values of the child nodes.
* @author talm
*
*/
protected class Node {
/**
* Value of the node. This value is a commitment to the values of its children.
*/
C hash;
/**
* Parent of this node in the tree. The root has a null parent.
*/
Node parent;
/**
* Pointer to left child. Leaves have null children.
*/
Node left;
/**
* Number of leaves under the left child.
*/
int leftSubtreeSize;
/**
* Pointer to right child. Leaves have null children.
*/
Node right;
/**
* Number of leaves under the right child.
*/
int rightSubtreeSize;
void updateHash() {
C leftHash = left == null ? null : left.hash;
C rightHash = right == null ? null : right.hash;
hash = hashfunc.hash(new Pair<C, C>(leftHash, rightHash));
}
}
protected MerkleTree() {
root = new Node();
depth = 0;
leafToNode = new GenericsUtils.HashMap<C, Node>();
}
public MerkleTree(CollisionResistantHash<C, Pair<C, C>> hashfunc) {
this();
this.hashfunc = hashfunc;
}
public C getRoot() {
return root.hash;
}
/**
* Add a leaf to the tree.
* @param leafvalue
* @return true if the leaf was added, false if it was already in the tree.
*/
public boolean addLeaf(C leafvalue) {
if (leafToNode.containsKey(leafvalue))
return false;
Node curNode = root;
Node leafNode = new Node();
leafNode.hash = leafvalue;
leafToNode.put(leafvalue, leafNode);
if (root.left == null) {
assert root.right == null;
root.left = leafNode;
leafNode.parent = root;
root.leftSubtreeSize = 1;
root.updateHash();
depth = 1;
} else if (root.right == null) {
root.right = leafNode;
leafNode.parent = root;
root.rightSubtreeSize = 1;
root.updateHash();
} else {
/*
* Repeatedly choose the child with the smallest subtree until
* we reach a leaf.
*/
int curdepth = 0;
while(curNode.leftSubtreeSize > 0) {
if (curNode.leftSubtreeSize > curNode.rightSubtreeSize)
curNode = curNode.right;
else
curNode = curNode.left;
++curdepth;
}
assert curdepth <= depth;
// We've reached a leaf.
assert curNode.rightSubtreeSize == 0;
// Create a new internal node, and insert it in place of curNode.
// curNode will become the new left node, and the new leaf will become
// its new right node.
Node newInternal = new Node();
newInternal.leftSubtreeSize = newInternal.rightSubtreeSize = 1;
newInternal.parent = curNode.parent;
if (curNode.parent.left == curNode) {
curNode.parent.left = newInternal;
} else {
assert curNode.parent.right == curNode;
curNode.parent.right = newInternal;
}
newInternal.left = curNode;
newInternal.right = leafNode;
leafNode.parent = curNode.parent = newInternal;
newInternal.updateHash();
if (curdepth == depth)
++depth;
// Update the subtree counts and hashes on the path to the root.
for (curNode = newInternal.parent; curNode != null; curNode = curNode.parent) {
curNode.leftSubtreeSize = curNode.left.leftSubtreeSize + curNode.left.rightSubtreeSize;
curNode.rightSubtreeSize = curNode.right.leftSubtreeSize + curNode.right.rightSubtreeSize;
curNode.updateHash();
}
}
return true;
}
/**
* Return a path from the leaf to the root.
* The path consists of a list of hash pairs, such that one element
* of each pair is a commitment to the two elements in the previous
* pair, and the first pair contains the leaf as one of the elements.
* @param leaf
* @return the path from the leaf to the root, or null if the leaf
* is not in the tree.
*/
public List<Pair<C,C>> getPath(C leaf) {
Node curNode = leafToNode.get(leaf);
if (curNode == null)
return null;
List<Pair<C,C>> path = new ArrayList<Pair<C,C>>(depth);
for (curNode = curNode.parent; curNode != null; curNode = curNode.parent) {
// The tree is left-leaning -- since there exists at least one node,
// the left child of every non-leaf node must exist.
assert curNode.left != null;
path.add(new Pair<C, C>(curNode.left.hash, curNode.right != null ? curNode.right.hash : null));
}
return path;
}
/**
* Verify that a path is a valid Merkle-tree path from a given leaf to a given
* tree root.
*
* @param leaf the leaf at which the path should start
* @param root the root of the tree to which the path root is compared.
* @param path the path to verify.
* @return true iff the first pair in the path contains the leaf, the hash of the final pair is the root,
* and each pair in the path contains the hash of the previous pair.
*/
public boolean verifyPath(C leaf, C root, List<Pair<C,C>> path) {
// Verify that the each pair contains a commitment
// to the previous pair and that the first pair
// in the path contains the leaf
C lasthash = leaf;
for (Pair<C,C> pair : path) {
if (!GenericsUtils.deepEquals(pair.a, lasthash) && !GenericsUtils.deepEquals(pair.b, lasthash))
return false;
lasthash = hashfunc.hash(pair);
}
// Verify that the path ends in root.
if (!GenericsUtils.deepEquals(lasthash, root))
return false;
// All the tests passed.
return true;
}
/**
* This is a utility class for serializing a path.
* @author talm
*
*/
public class PathEncoder implements StreamEncoder<List<Pair<C,C>>> {
StreamEncoder<C> cEncoder;
public PathEncoder(StreamEncoder<C> cEncoder) {
this.cEncoder = cEncoder;
}
@Override
public List<Pair<C, C>> decode(InputStream in) throws IOException {
int n = EncodingUtils.decodeInt(in);
List<Pair<C,C>> list = new ArrayList<Pair<C,C>>(n);
for (int i = 0; i < n; ++i) {
C a = cEncoder.decode(in);
C b = cEncoder.decode(in);
list.add(new Pair<C, C>(a,b));
}
return list;
}
@Override
public int encode(List<Pair<C, C>> input, OutputStream out)
throws IOException {
int pos = 0;
// Encode length of list
pos += EncodingUtils.encode(input.size(), out);
// Encode list elements
for (Pair<C,C> item : input) {
pos += cEncoder.encode(item.a, out);
pos += cEncoder.encode(item.b, out);
}
return pos;
}
}
}
| UTF-8 | Java | 7,477 | java | MerkleTree.java | Java | [
{
"context": "ing a generic collision-resistant hash.\n * @author talm\n *\n * @param <C> The type determining the range a",
"end": 480,
"score": 0.9995375871658325,
"start": 476,
"tag": "USERNAME",
"value": "talm"
},
{
"context": "hashing the values of the child nodes.\n\t * @author talm\n\t *\n\t */\n\tprotected class Node {\n\t\t/**\n\t\t * Value",
"end": 1310,
"score": 0.999538779258728,
"start": 1306,
"tag": "USERNAME",
"value": "talm"
},
{
"context": " utility class for serializing a path.\n\t * @author talm\n\t *\n\t */\n\tpublic class PathEncoder implements St",
"end": 6574,
"score": 0.9995423555374146,
"start": 6570,
"tag": "USERNAME",
"value": "talm"
}
] | null | [] | package qilin.primitives.generic;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import qilin.primitives.CollisionResistantHash;
import qilin.util.EncodingUtils;
import qilin.util.GenericsUtils;
import qilin.util.Pair;
import qilin.util.StreamEncoder;
/**
* Implmentation of a binary Merkle tree commitment using a generic collision-resistant hash.
* @author talm
*
* @param <C> The type determining the range and domain of the collision-resistant hash.
* The hash function must map a pair of elements of this type to a single element of
* this type.
*
* @see CollisionResistantHash
*/
public class MerkleTree<C> {
/**
* The hash function used to generate the Merkle tree.
*/
protected CollisionResistantHash<C, Pair<C, C>> hashfunc;
/**
* The root of the Merkle Tree.
*/
protected Node root;
/**
* The maximum length of a path from a leaf to the root.
*/
protected int depth;
/**
* A map from leaf hashvalues to the nodes that represent them.
*/
Map<C, Node> leafToNode;
/**
* A node in the Merkle tree. Each node has a value and pointers to its child nodes.
* The value is computed by hashing the values of the child nodes.
* @author talm
*
*/
protected class Node {
/**
* Value of the node. This value is a commitment to the values of its children.
*/
C hash;
/**
* Parent of this node in the tree. The root has a null parent.
*/
Node parent;
/**
* Pointer to left child. Leaves have null children.
*/
Node left;
/**
* Number of leaves under the left child.
*/
int leftSubtreeSize;
/**
* Pointer to right child. Leaves have null children.
*/
Node right;
/**
* Number of leaves under the right child.
*/
int rightSubtreeSize;
void updateHash() {
C leftHash = left == null ? null : left.hash;
C rightHash = right == null ? null : right.hash;
hash = hashfunc.hash(new Pair<C, C>(leftHash, rightHash));
}
}
protected MerkleTree() {
root = new Node();
depth = 0;
leafToNode = new GenericsUtils.HashMap<C, Node>();
}
public MerkleTree(CollisionResistantHash<C, Pair<C, C>> hashfunc) {
this();
this.hashfunc = hashfunc;
}
public C getRoot() {
return root.hash;
}
/**
* Add a leaf to the tree.
* @param leafvalue
* @return true if the leaf was added, false if it was already in the tree.
*/
public boolean addLeaf(C leafvalue) {
if (leafToNode.containsKey(leafvalue))
return false;
Node curNode = root;
Node leafNode = new Node();
leafNode.hash = leafvalue;
leafToNode.put(leafvalue, leafNode);
if (root.left == null) {
assert root.right == null;
root.left = leafNode;
leafNode.parent = root;
root.leftSubtreeSize = 1;
root.updateHash();
depth = 1;
} else if (root.right == null) {
root.right = leafNode;
leafNode.parent = root;
root.rightSubtreeSize = 1;
root.updateHash();
} else {
/*
* Repeatedly choose the child with the smallest subtree until
* we reach a leaf.
*/
int curdepth = 0;
while(curNode.leftSubtreeSize > 0) {
if (curNode.leftSubtreeSize > curNode.rightSubtreeSize)
curNode = curNode.right;
else
curNode = curNode.left;
++curdepth;
}
assert curdepth <= depth;
// We've reached a leaf.
assert curNode.rightSubtreeSize == 0;
// Create a new internal node, and insert it in place of curNode.
// curNode will become the new left node, and the new leaf will become
// its new right node.
Node newInternal = new Node();
newInternal.leftSubtreeSize = newInternal.rightSubtreeSize = 1;
newInternal.parent = curNode.parent;
if (curNode.parent.left == curNode) {
curNode.parent.left = newInternal;
} else {
assert curNode.parent.right == curNode;
curNode.parent.right = newInternal;
}
newInternal.left = curNode;
newInternal.right = leafNode;
leafNode.parent = curNode.parent = newInternal;
newInternal.updateHash();
if (curdepth == depth)
++depth;
// Update the subtree counts and hashes on the path to the root.
for (curNode = newInternal.parent; curNode != null; curNode = curNode.parent) {
curNode.leftSubtreeSize = curNode.left.leftSubtreeSize + curNode.left.rightSubtreeSize;
curNode.rightSubtreeSize = curNode.right.leftSubtreeSize + curNode.right.rightSubtreeSize;
curNode.updateHash();
}
}
return true;
}
/**
* Return a path from the leaf to the root.
* The path consists of a list of hash pairs, such that one element
* of each pair is a commitment to the two elements in the previous
* pair, and the first pair contains the leaf as one of the elements.
* @param leaf
* @return the path from the leaf to the root, or null if the leaf
* is not in the tree.
*/
public List<Pair<C,C>> getPath(C leaf) {
Node curNode = leafToNode.get(leaf);
if (curNode == null)
return null;
List<Pair<C,C>> path = new ArrayList<Pair<C,C>>(depth);
for (curNode = curNode.parent; curNode != null; curNode = curNode.parent) {
// The tree is left-leaning -- since there exists at least one node,
// the left child of every non-leaf node must exist.
assert curNode.left != null;
path.add(new Pair<C, C>(curNode.left.hash, curNode.right != null ? curNode.right.hash : null));
}
return path;
}
/**
* Verify that a path is a valid Merkle-tree path from a given leaf to a given
* tree root.
*
* @param leaf the leaf at which the path should start
* @param root the root of the tree to which the path root is compared.
* @param path the path to verify.
* @return true iff the first pair in the path contains the leaf, the hash of the final pair is the root,
* and each pair in the path contains the hash of the previous pair.
*/
public boolean verifyPath(C leaf, C root, List<Pair<C,C>> path) {
// Verify that the each pair contains a commitment
// to the previous pair and that the first pair
// in the path contains the leaf
C lasthash = leaf;
for (Pair<C,C> pair : path) {
if (!GenericsUtils.deepEquals(pair.a, lasthash) && !GenericsUtils.deepEquals(pair.b, lasthash))
return false;
lasthash = hashfunc.hash(pair);
}
// Verify that the path ends in root.
if (!GenericsUtils.deepEquals(lasthash, root))
return false;
// All the tests passed.
return true;
}
/**
* This is a utility class for serializing a path.
* @author talm
*
*/
public class PathEncoder implements StreamEncoder<List<Pair<C,C>>> {
StreamEncoder<C> cEncoder;
public PathEncoder(StreamEncoder<C> cEncoder) {
this.cEncoder = cEncoder;
}
@Override
public List<Pair<C, C>> decode(InputStream in) throws IOException {
int n = EncodingUtils.decodeInt(in);
List<Pair<C,C>> list = new ArrayList<Pair<C,C>>(n);
for (int i = 0; i < n; ++i) {
C a = cEncoder.decode(in);
C b = cEncoder.decode(in);
list.add(new Pair<C, C>(a,b));
}
return list;
}
@Override
public int encode(List<Pair<C, C>> input, OutputStream out)
throws IOException {
int pos = 0;
// Encode length of list
pos += EncodingUtils.encode(input.size(), out);
// Encode list elements
for (Pair<C,C> item : input) {
pos += cEncoder.encode(item.a, out);
pos += cEncoder.encode(item.b, out);
}
return pos;
}
}
}
| 7,477 | 0.664839 | 0.663501 | 282 | 25.514185 | 24.756147 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.382979 | false | false | 9 |
6ac0e3cb016a293767fefaf38f02e1b454f6a162 | 39,530,879,032,988 | ddb2d71eec70dd48b60a58fb987307ae7804d0a0 | /Bank/src/bankproduct/BankProduct.java | 5646877e7ab970e778a692fce1e5b8b89372f5b0 | [] | no_license | pechorinn/OOP_Java_ItTalents_Camp | https://github.com/pechorinn/OOP_Java_ItTalents_Camp | d90b69975d7350f8d023e3e1e510358d1d33059a | 10daee11ac5c111a10cf821a6589fcf3c99c7b90 | refs/heads/master | 2021-01-22T21:07:25.311000 | 2017-10-08T19:21:13 | 2017-10-08T19:21:13 | 100,681,397 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package bankproduct;
import static bank.Verification.*;
import java.util.Random;
import client.Client;
public abstract class BankProduct {
protected Client client;
protected double interest;
protected int timePeriod;
protected double cash;
public BankProduct(Client client, int timePeriod) {
super();
this.client = client;
checkIfInputPositiveAndNotEqualToZero(timePeriod);
this.timePeriod = timePeriod;
this.interest = new Random().nextInt(16) + 5;
}
public double getInterest() {
return interest;
}
public Client getClient() {
return client;
}
public double getCash() {
return cash;
}
public void addCash(double amount) {
cash += amount;
}
public int getTimePeriod() {
return timePeriod;
}
}
| UTF-8 | Java | 752 | java | BankProduct.java | Java | [] | null | [] | package bankproduct;
import static bank.Verification.*;
import java.util.Random;
import client.Client;
public abstract class BankProduct {
protected Client client;
protected double interest;
protected int timePeriod;
protected double cash;
public BankProduct(Client client, int timePeriod) {
super();
this.client = client;
checkIfInputPositiveAndNotEqualToZero(timePeriod);
this.timePeriod = timePeriod;
this.interest = new Random().nextInt(16) + 5;
}
public double getInterest() {
return interest;
}
public Client getClient() {
return client;
}
public double getCash() {
return cash;
}
public void addCash(double amount) {
cash += amount;
}
public int getTimePeriod() {
return timePeriod;
}
}
| 752 | 0.718085 | 0.714096 | 45 | 15.711111 | 15.29651 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.422222 | false | false | 9 |
c4a4c0051e045391b7133682cd76d22d0e169186 | 35,966,056,182,310 | 583104b5c2ee4ec4b2a3187b3b79ac665f65868b | /src/main/java/br/com/controlefinanceiro/service/IncomeService.java | 7d25c32e3fe2cf70cd0b04f64ac13b5e478713ee | [
"MIT"
] | permissive | JavesonYehudi/controle-financeiro-ws | https://github.com/JavesonYehudi/controle-financeiro-ws | 899fb4e35e7f642f682cf8f32aa9e1317b51da11 | eae0aa5956ae072eb443555a03075dd908ff1e12 | refs/heads/master | 2021-11-30T21:17:14.569000 | 2021-11-28T19:56:44 | 2021-11-28T19:56:44 | 80,247,603 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.com.controlefinanceiro.service;
import java.util.List;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.inject.Named;
import org.bson.types.ObjectId;
import br.com.controlefinanceiro.dao.GenericDao;
import br.com.controlefinanceiro.model.Funds;
import br.com.controlefinanceiro.model.Income;
import br.com.controlefinanceiro.model.Payment;
@RequestScoped
@Named("income")
public class IncomeService extends GenericService<Income> implements IFinancialTransactionService<Income> {
@Inject
private GenericDao<Income> dao;
@Inject
private GenericDao<Funds> fundsDao;
@Override
public Income pay(ObjectId id, Payment payment) throws Exception {
Income income = dao.find(id);
income.addPayment(payment);
return dao.update(income);
}
@Override
public Income create(Income income) {
income.setValueTransaction(income.getValueTransaction().abs());
income.setFunds(fundsDao.find(income.getFunds().getId()));
income.setLastMaturity(income.getFirstMaturity().plus(income.getRecurrent(), income.getCalendarPeriod().getChronoUnit()));
return dao.create(income);
}
@Override
public List<Income> list() {
return dao.list();
}
@Override
public Income find(ObjectId id) {
return dao.find(id);
}
@Override
public Income update(ObjectId id, Income income) {
Income incomeAux = dao.find(id);
incomeAux.setDescription(income.getDescription());
incomeAux.setFunds(income.getFunds());
incomeAux.setGroup(income.getGroup());
incomeAux.setFixedTransaction(income.isFixedTransaction());
incomeAux.setValueTransaction(income.getValueTransaction());
incomeAux.setRecurrent(income.getRecurrent());
return dao.update(incomeAux);
}
} | UTF-8 | Java | 1,720 | java | IncomeService.java | Java | [] | null | [] | package br.com.controlefinanceiro.service;
import java.util.List;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.inject.Named;
import org.bson.types.ObjectId;
import br.com.controlefinanceiro.dao.GenericDao;
import br.com.controlefinanceiro.model.Funds;
import br.com.controlefinanceiro.model.Income;
import br.com.controlefinanceiro.model.Payment;
@RequestScoped
@Named("income")
public class IncomeService extends GenericService<Income> implements IFinancialTransactionService<Income> {
@Inject
private GenericDao<Income> dao;
@Inject
private GenericDao<Funds> fundsDao;
@Override
public Income pay(ObjectId id, Payment payment) throws Exception {
Income income = dao.find(id);
income.addPayment(payment);
return dao.update(income);
}
@Override
public Income create(Income income) {
income.setValueTransaction(income.getValueTransaction().abs());
income.setFunds(fundsDao.find(income.getFunds().getId()));
income.setLastMaturity(income.getFirstMaturity().plus(income.getRecurrent(), income.getCalendarPeriod().getChronoUnit()));
return dao.create(income);
}
@Override
public List<Income> list() {
return dao.list();
}
@Override
public Income find(ObjectId id) {
return dao.find(id);
}
@Override
public Income update(ObjectId id, Income income) {
Income incomeAux = dao.find(id);
incomeAux.setDescription(income.getDescription());
incomeAux.setFunds(income.getFunds());
incomeAux.setGroup(income.getGroup());
incomeAux.setFixedTransaction(income.isFixedTransaction());
incomeAux.setValueTransaction(income.getValueTransaction());
incomeAux.setRecurrent(income.getRecurrent());
return dao.update(incomeAux);
}
} | 1,720 | 0.776744 | 0.776744 | 63 | 26.317461 | 25.973017 | 124 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.380952 | false | false | 9 |
5a6359204981f99218954567f839bc26932b88ce | 25,761,213,905,544 | a507f69b310dbbf7e2eebb249453b74c461347c6 | /Employee scheduler/apigateway/src/main/java/com/mhp/apigateway/mapper/ApiGatewayTeamLeadMapper.java | ac6ff0298c0b5abf11dc38ee1e8d903f7fb296cb | [] | no_license | SiposAndrei/Projects | https://github.com/SiposAndrei/Projects | 311a76ed660b93140b4c2b0813e2a08f34da2a32 | c0e2da21296c266e1c201d78fdf549c0b2ef1e3b | refs/heads/master | 2019-12-13T20:13:04.547000 | 2019-05-03T20:16:41 | 2019-05-03T20:16:41 | 101,922,125 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.mhp.apigateway.mapper;
import org.springframework.stereotype.Service;
import com.mhp.apigateway.epo.ApiGatewayTeamLeadEpo;
import com.mhp.usersmicro.epo.TeamLeadEpo;
@Service
public class ApiGatewayTeamLeadMapper extends AbstractMapper<TeamLeadEpo, ApiGatewayTeamLeadEpo> {
@Override
public TeamLeadEpo toInternal(ApiGatewayTeamLeadEpo epo) {
TeamLeadEpo tl = new TeamLeadEpo(epo.getId(), epo.getFirstName(), epo.getLastName(), epo.getUsername(),
epo.getPassword(), epo.getUserType(), epo.getUserPosition(), epo.getPhoto(), epo.getDepartment(),
epo.getSkills(), epo.getLanguages(), epo.getTeams());
return tl;
}
@Override
public ApiGatewayTeamLeadEpo toExternal(TeamLeadEpo tl) {
ApiGatewayTeamLeadEpo epo = new ApiGatewayTeamLeadEpo(tl.getId(), tl.getFirstName(), tl.getLastName(),
tl.getUsername(), tl.getPassword(), tl.getUserType(), tl.getUserPosition(), tl.getPhoto(), tl.getDepartment(),
tl.getSkills(), tl.getLanguages(), tl.getTeams());
return epo;
}
}
| UTF-8 | Java | 1,066 | java | ApiGatewayTeamLeadMapper.java | Java | [] | null | [] | package com.mhp.apigateway.mapper;
import org.springframework.stereotype.Service;
import com.mhp.apigateway.epo.ApiGatewayTeamLeadEpo;
import com.mhp.usersmicro.epo.TeamLeadEpo;
@Service
public class ApiGatewayTeamLeadMapper extends AbstractMapper<TeamLeadEpo, ApiGatewayTeamLeadEpo> {
@Override
public TeamLeadEpo toInternal(ApiGatewayTeamLeadEpo epo) {
TeamLeadEpo tl = new TeamLeadEpo(epo.getId(), epo.getFirstName(), epo.getLastName(), epo.getUsername(),
epo.getPassword(), epo.getUserType(), epo.getUserPosition(), epo.getPhoto(), epo.getDepartment(),
epo.getSkills(), epo.getLanguages(), epo.getTeams());
return tl;
}
@Override
public ApiGatewayTeamLeadEpo toExternal(TeamLeadEpo tl) {
ApiGatewayTeamLeadEpo epo = new ApiGatewayTeamLeadEpo(tl.getId(), tl.getFirstName(), tl.getLastName(),
tl.getUsername(), tl.getPassword(), tl.getUserType(), tl.getUserPosition(), tl.getPhoto(), tl.getDepartment(),
tl.getSkills(), tl.getLanguages(), tl.getTeams());
return epo;
}
}
| 1,066 | 0.72045 | 0.72045 | 27 | 38.48148 | 39.396721 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.148148 | false | false | 9 |
68f2d92a8d6575d6e43261152803a896e0cdd008 | 8,323,646,635,388 | 896a21136006b7915f9b3b90d5dd0c2c2b6fbd5b | /teacher-manage/src/main/java/com/xrjj/util/Poi.java | c7f87db4fa6f87a970a7d3cffcb63f98c528a8e0 | [] | no_license | kingzxli/teach-manage | https://github.com/kingzxli/teach-manage | b238d2c295317cae93050391b8e807606727206a | 1323b7a1cfa0a392152e10ef06f59a3fd73f9f92 | refs/heads/master | 2023-04-01T03:45:48.151000 | 2021-04-10T02:40:10 | 2021-04-10T02:40:10 | 356,449,567 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.xrjj.util;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;
import com.xrjj.exception.CustomException;
/**
* excel操作
* @author king
*
*/
public class Poi {
private static final String XLS = ".xls";
private static final String XLSX = ".xlsx";
public static Sheet read(MultipartFile file) {
Sheet sheet = null;
try {
String fileName = file.getOriginalFilename();
String fileType = fileName.substring(fileName.lastIndexOf("."));
Workbook workbook = null;
if (XLS.equalsIgnoreCase(fileType)) {
workbook = new HSSFWorkbook(file.getInputStream());
} else if (XLSX.equalsIgnoreCase(fileType)) {
workbook = new XSSFWorkbook(file.getInputStream());
}
sheet = workbook.getSheetAt(0);
} catch (Exception e) {
throw new CustomException("文件读取异常, " + e.getMessage());
}
return sheet;
}
/**
* 读入excel的内容转换成字符串
*
* @author Rex.Tan
* @date 2019年11月29日 下午2:24:04
* @param cell
* @return
*/
@SuppressWarnings("deprecation")
public static String getStringValueFromCell(Cell cell) {
String value = "";
if (cell == null) {
return value;
}
// 判断数据类型
switch (cell.getCellType()) {
case 2://FORMULA
value = "" + cell.getCellFormula();
break;
case 0: //NUMERIC
if (DateUtil.isCellDateFormatted(cell)) {
Date date = cell.getDateCellValue();
return date2StringNormal(date, null);
} else {
cell.setCellType(CellType.STRING);
value = "" + cell.getStringCellValue();
if (value.endsWith(".0")) {
value = value.substring(0, value.indexOf("."));
}
}
break;
case 1: //String
value = cell.getStringCellValue();
break;
default:
break;
}
if(value != null) {
value = value.trim();
}
return value;
}
public static String date2StringNormal(Date date, String format) {
if(date == null) {
return "";
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
if(StringUtils.isNotBlank(format)) {
sdf = new SimpleDateFormat(format);
}
return sdf.format(date);
}
}
| UTF-8 | Java | 2,565 | java | Poi.java | Java | [
{
"context": "eption.CustomException;\n\n/**\n * excel操作\n * @author king\n *\n */\npublic class Poi {\n\tprivate static final S",
"end": 577,
"score": 0.9919068217277527,
"start": 573,
"tag": "USERNAME",
"value": "king"
},
{
"context": "t;\n\t}\n\t\n\t/**\n\t * 读入excel的内容转换成字符串\n\t * \n\t * @author Rex.Tan\n\t * @date 2019年11月29日 下午2:24:04\n\t * @param cell\n\t",
"end": 1366,
"score": 0.9995763897895813,
"start": 1359,
"tag": "NAME",
"value": "Rex.Tan"
}
] | null | [] | package com.xrjj.util;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;
import com.xrjj.exception.CustomException;
/**
* excel操作
* @author king
*
*/
public class Poi {
private static final String XLS = ".xls";
private static final String XLSX = ".xlsx";
public static Sheet read(MultipartFile file) {
Sheet sheet = null;
try {
String fileName = file.getOriginalFilename();
String fileType = fileName.substring(fileName.lastIndexOf("."));
Workbook workbook = null;
if (XLS.equalsIgnoreCase(fileType)) {
workbook = new HSSFWorkbook(file.getInputStream());
} else if (XLSX.equalsIgnoreCase(fileType)) {
workbook = new XSSFWorkbook(file.getInputStream());
}
sheet = workbook.getSheetAt(0);
} catch (Exception e) {
throw new CustomException("文件读取异常, " + e.getMessage());
}
return sheet;
}
/**
* 读入excel的内容转换成字符串
*
* @author Rex.Tan
* @date 2019年11月29日 下午2:24:04
* @param cell
* @return
*/
@SuppressWarnings("deprecation")
public static String getStringValueFromCell(Cell cell) {
String value = "";
if (cell == null) {
return value;
}
// 判断数据类型
switch (cell.getCellType()) {
case 2://FORMULA
value = "" + cell.getCellFormula();
break;
case 0: //NUMERIC
if (DateUtil.isCellDateFormatted(cell)) {
Date date = cell.getDateCellValue();
return date2StringNormal(date, null);
} else {
cell.setCellType(CellType.STRING);
value = "" + cell.getStringCellValue();
if (value.endsWith(".0")) {
value = value.substring(0, value.indexOf("."));
}
}
break;
case 1: //String
value = cell.getStringCellValue();
break;
default:
break;
}
if(value != null) {
value = value.trim();
}
return value;
}
public static String date2StringNormal(Date date, String format) {
if(date == null) {
return "";
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
if(StringUtils.isNotBlank(format)) {
sdf = new SimpleDateFormat(format);
}
return sdf.format(date);
}
}
| 2,565 | 0.674651 | 0.665868 | 98 | 24.561224 | 19.529709 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.071429 | false | false | 9 |
27288c99956938010a986fb5c78b065a8f8f5d91 | 8,323,646,634,244 | e593fd8902ef395b2c1626a3126a4e0002e2c0df | /app/src/main/java/com/warrous/ready2ride/facebookfriendslist/ui/main/MainView.java | d3fc67743762224c4dd7d3f5f0918df13f1058b9 | [] | no_license | AshaPemma/Ready2Ride | https://github.com/AshaPemma/Ready2Ride | 3d1c93a7e5d1f31469abf9d255ab5382871a13e4 | 8308c0cd51e113a347a19c165c0a6e6ff3cc000e | refs/heads/master | 2022-02-12T11:19:07.178000 | 2019-07-23T05:20:12 | 2019-07-23T05:20:12 | 198,356,504 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.warrous.ready2ride.facebookfriendslist.ui.main;
import com.facebook.AccessToken;
/**
* Created by Sally on 01-Jan-17.
*/
public interface MainView {
void initializeFBSdk();
void initializeView();
void showFriendsList();
void showFBLoginResult(AccessToken fbAccessToken);
void loginUsingFBManager();
}
| UTF-8 | Java | 342 | java | MainView.java | Java | [
{
"context": "mport com.facebook.AccessToken;\n\n/**\n * Created by Sally on 01-Jan-17.\n */\n\npublic interface MainView {\n ",
"end": 118,
"score": 0.9991151094436646,
"start": 113,
"tag": "NAME",
"value": "Sally"
}
] | null | [] | package com.warrous.ready2ride.facebookfriendslist.ui.main;
import com.facebook.AccessToken;
/**
* Created by Sally on 01-Jan-17.
*/
public interface MainView {
void initializeFBSdk();
void initializeView();
void showFriendsList();
void showFBLoginResult(AccessToken fbAccessToken);
void loginUsingFBManager();
}
| 342 | 0.730994 | 0.716374 | 19 | 17 | 19.004154 | 59 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.368421 | false | false | 9 |
3d6096376510297153692c2a2e170850c32fcd23 | 8,323,646,634,605 | 44d041667d54d8eaaa89bfced19fac0ddb6f76c8 | /airavata-rest-security/modules/security/src/main/java/org/apache/airavata/security/userstore/AbstractJDBCUserStore.java | 80a72bbd6e1959a677dab66a1132f9b8ae4156cb | [] | no_license | apache/airavata-sandbox | https://github.com/apache/airavata-sandbox | 7f2bc0550fe64ee1ee8ad40d6a5abb2a44be596a | fabf8b7d753570f2404f2d9830c59786a8c78468 | refs/heads/master | 2023-09-04T06:34:34.830000 | 2023-03-27T18:33:51 | 2023-03-27T19:03:58 | 20,473,416 | 3 | 43 | null | false | 2023-09-06T20:29:39 | 2014-06-04T07:00:07 | 2023-01-31T16:34:15 | 2023-09-06T20:29:32 | 30,984 | 1 | 24 | 79 | JavaScript | false | false | /*
*
* *
* * Licensed to the Apache Software Foundation (ASF) under one
* * or more contributor license agreements. See the NOTICE file
* * distributed with this work for additional information
* * regarding copyright ownership. The ASF licenses this file
* * to you under the Apache License, Version 2.0 (the
* * "License"); you may not use this file except in compliance
* * with the License. You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing,
* * software distributed under the License is distributed on an
* * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* * KIND, either express or implied. See the License for the
* * specific language governing permissions and limitations
* * under the License.
* *
*
*/
package org.apache.airavata.security.userstore;
import org.apache.airavata.security.UserStore;
import org.apache.airavata.security.UserStoreException;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* An abstract implementation of the UserStore. This will encapsulate
* JDBC configurations reading code.
*/
public abstract class AbstractJDBCUserStore implements UserStore {
private String databaseURL = null;
private String databaseDriver = null;
private String databaseUserName = null;
private String databasePassword = null;
public String getDatabaseURL() {
return databaseURL;
}
public String getDatabaseDriver() {
return databaseDriver;
}
public String getDatabaseUserName() {
return databaseUserName;
}
public String getDatabasePassword() {
return databasePassword;
}
/**
* Configures primary JDBC parameters. i.e
* @param node An XML configuration node.
* @throws UserStoreException
*/
public void configure(Node node) throws UserStoreException{
/**
<specificConfigurations>
<database>
<jdbcUrl></jdbcUrl>
<databaseDriver></databaseDriver>
<userName></userName>
<password></password>
</database>
</specificConfigurations>
*/
NodeList databaseNodeList = node.getChildNodes();
Node databaseNode = null;
for (int k = 0; k < databaseNodeList.getLength(); ++k) {
Node n = databaseNodeList.item(k);
if (n != null && n.getNodeType() == Node.ELEMENT_NODE) {
databaseNode = n;
}
}
if (databaseNode != null) {
NodeList nodeList = databaseNode.getChildNodes();
for (int i = 0; i < nodeList.getLength(); ++i) {
Node n = nodeList.item(i);
if (n.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) n;
if (element.getNodeName().equals("jdbcUrl")) {
databaseURL = element.getFirstChild().getNodeValue();
} else if (element.getNodeName().equals("databaseDriver")) {
databaseDriver = element.getFirstChild().getNodeValue();
} else if (element.getNodeName().equals("userName")) {
databaseUserName = element.getFirstChild().getNodeValue();
} else if (element.getNodeName().equals("password")) {
databasePassword = element.getFirstChild().getNodeValue();
}
}
}
}
}
}
| UTF-8 | Java | 3,604 | java | AbstractJDBCUserStore.java | Java | [
{
"context": "Name = null;\n private String databasePassword = null;\n\n public String getDatabaseURL() {\n re",
"end": 1461,
"score": 0.9126105904579163,
"start": 1457,
"tag": "PASSWORD",
"value": "null"
}
] | null | [] | /*
*
* *
* * Licensed to the Apache Software Foundation (ASF) under one
* * or more contributor license agreements. See the NOTICE file
* * distributed with this work for additional information
* * regarding copyright ownership. The ASF licenses this file
* * to you under the Apache License, Version 2.0 (the
* * "License"); you may not use this file except in compliance
* * with the License. You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing,
* * software distributed under the License is distributed on an
* * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* * KIND, either express or implied. See the License for the
* * specific language governing permissions and limitations
* * under the License.
* *
*
*/
package org.apache.airavata.security.userstore;
import org.apache.airavata.security.UserStore;
import org.apache.airavata.security.UserStoreException;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* An abstract implementation of the UserStore. This will encapsulate
* JDBC configurations reading code.
*/
public abstract class AbstractJDBCUserStore implements UserStore {
private String databaseURL = null;
private String databaseDriver = null;
private String databaseUserName = null;
private String databasePassword = <PASSWORD>;
public String getDatabaseURL() {
return databaseURL;
}
public String getDatabaseDriver() {
return databaseDriver;
}
public String getDatabaseUserName() {
return databaseUserName;
}
public String getDatabasePassword() {
return databasePassword;
}
/**
* Configures primary JDBC parameters. i.e
* @param node An XML configuration node.
* @throws UserStoreException
*/
public void configure(Node node) throws UserStoreException{
/**
<specificConfigurations>
<database>
<jdbcUrl></jdbcUrl>
<databaseDriver></databaseDriver>
<userName></userName>
<password></password>
</database>
</specificConfigurations>
*/
NodeList databaseNodeList = node.getChildNodes();
Node databaseNode = null;
for (int k = 0; k < databaseNodeList.getLength(); ++k) {
Node n = databaseNodeList.item(k);
if (n != null && n.getNodeType() == Node.ELEMENT_NODE) {
databaseNode = n;
}
}
if (databaseNode != null) {
NodeList nodeList = databaseNode.getChildNodes();
for (int i = 0; i < nodeList.getLength(); ++i) {
Node n = nodeList.item(i);
if (n.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) n;
if (element.getNodeName().equals("jdbcUrl")) {
databaseURL = element.getFirstChild().getNodeValue();
} else if (element.getNodeName().equals("databaseDriver")) {
databaseDriver = element.getFirstChild().getNodeValue();
} else if (element.getNodeName().equals("userName")) {
databaseUserName = element.getFirstChild().getNodeValue();
} else if (element.getNodeName().equals("password")) {
databasePassword = element.getFirstChild().getNodeValue();
}
}
}
}
}
}
| 3,610 | 0.611543 | 0.609046 | 115 | 30.33913 | 26.216122 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.295652 | false | false | 9 |
e3ba03b0be9c6ba584c091ae4bfad2434141669a | 12,618,613,920,132 | e072de6d7171320dea8cc7e36949fba2aaff35d5 | /Casilla.java | 3b5a1051b509965812dc8842a515914f26c8a46e | [
"MIT"
] | permissive | gdaguilarc/Java-Louvre-RPG | https://github.com/gdaguilarc/Java-Louvre-RPG | 356367bdd027ebf3a39af4b35281600a56c4adf4 | 02aa5cd6ff6ad28eef6260b266d31dfc5afe8333 | refs/heads/master | 2021-05-02T17:37:02.766000 | 2019-06-04T04:57:36 | 2019-06-04T04:57:36 | 120,648,997 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.io.Serializable;
public class Casilla extends Mapa implements Serializable {
private static final long serialVersionUID = 1L;
private Personaje enemigo;
private Objeto objeto;
public Casilla(int aleatorio, int aleatorio2) {
switch (aleatorio) {
case 1:
this.enemigo = new Momia();
break;
case 2:
this.enemigo = new Pintura();
break;
case 3:
this.enemigo = new Escultura();
break;
}
switch (aleatorio2) {
case 1:
this.objeto = new LibroDeArte();
break;
case 2:
this.objeto = new LibroDeHistoria();
break;
case 3:
this.objeto = new Camara();
break;
case 4:
this.objeto = new Pincel();
break;
case 5:
this.objeto = new Pc();
break;
}
}
public Casilla(int contador) {
switch (contador) {
case 1:
this.enemigo = new ElHamurabi();
break;
case 4:
this.enemigo = new LaGioconda();
break;
case 2:
this.enemigo = new LaLibertadGuiandoAlPueblo();
break;
case 3:
this.enemigo = new LaVenusDeMilo();
break;
}
this.objeto = new TurboPoder();
}
public Casilla() {
this.objeto = objeto;
this.enemigo = enemigo;
}
public Personaje getEnemigo() {
return enemigo;
}
public Personaje getEnemigoVivo() throws ZombieException {
if (enemigo.getVida() <= 0) {
throw new ZombieException();
} else {
return enemigo;
}
}
public Objeto getObjeto() {
return objeto;
}
}
| UTF-8 | Java | 1,407 | java | Casilla.java | Java | [] | null | [] | import java.io.Serializable;
public class Casilla extends Mapa implements Serializable {
private static final long serialVersionUID = 1L;
private Personaje enemigo;
private Objeto objeto;
public Casilla(int aleatorio, int aleatorio2) {
switch (aleatorio) {
case 1:
this.enemigo = new Momia();
break;
case 2:
this.enemigo = new Pintura();
break;
case 3:
this.enemigo = new Escultura();
break;
}
switch (aleatorio2) {
case 1:
this.objeto = new LibroDeArte();
break;
case 2:
this.objeto = new LibroDeHistoria();
break;
case 3:
this.objeto = new Camara();
break;
case 4:
this.objeto = new Pincel();
break;
case 5:
this.objeto = new Pc();
break;
}
}
public Casilla(int contador) {
switch (contador) {
case 1:
this.enemigo = new ElHamurabi();
break;
case 4:
this.enemigo = new LaGioconda();
break;
case 2:
this.enemigo = new LaLibertadGuiandoAlPueblo();
break;
case 3:
this.enemigo = new LaVenusDeMilo();
break;
}
this.objeto = new TurboPoder();
}
public Casilla() {
this.objeto = objeto;
this.enemigo = enemigo;
}
public Personaje getEnemigo() {
return enemigo;
}
public Personaje getEnemigoVivo() throws ZombieException {
if (enemigo.getVida() <= 0) {
throw new ZombieException();
} else {
return enemigo;
}
}
public Objeto getObjeto() {
return objeto;
}
}
| 1,407 | 0.649609 | 0.638237 | 79 | 16.810127 | 15.012296 | 59 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.291139 | false | false | 9 |
201bb3e8ce802bd1ed2fbf31d3bef3b1c02064af | 3,100,966,397,784 | 09d1eec61dd77ac7da61fbd089fa2da6aebf10dc | /src/main/java/wwii/cranes/service/event/EventService.java | 8ef363075e74876544b4ead0ba578531b48ce63c | [] | no_license | asyalushnikova/Cranes | https://github.com/asyalushnikova/Cranes | d43933e18fecac57f89e79d13d0b1415909362ba | 9c5a056c54add8a3a6472d9020d54d4c931ac762 | refs/heads/main | 2023-03-23T01:48:27.932000 | 2021-03-15T12:06:42 | 2021-03-15T12:06:42 | 277,404,052 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package wwii.cranes.service.event;
import wwii.cranes.model.event.Event;
import java.util.Optional;
public interface EventService {
Iterable<Event> findAllEvents();
Optional<Event> findEventById(Long event_id);
}
| UTF-8 | Java | 226 | java | EventService.java | Java | [] | null | [] | package wwii.cranes.service.event;
import wwii.cranes.model.event.Event;
import java.util.Optional;
public interface EventService {
Iterable<Event> findAllEvents();
Optional<Event> findEventById(Long event_id);
}
| 226 | 0.761062 | 0.761062 | 12 | 17.833334 | 18.356804 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.416667 | false | false | 9 |
93ea5d2dd4a25a33678c2a20f634ce8f0b8adfbd | 2,448,131,365,622 | 2733b59d83170fdd9c59ea12ebe8cc669f0416ef | /core-test/src/main/java/org/openstack4j/api/network/TrunkTests.java | af9f8b703f58bf99a6504ff3ca8c965c9b24fa67 | [
"Apache-2.0"
] | permissive | openstack4j/openstack4j | https://github.com/openstack4j/openstack4j | d10029c13a0c015cabd681646c6675a24c7804c0 | 80862e02ca140bc1c37dd029b08481d3cae5e192 | refs/heads/master | 2023-08-08T11:58:39.052000 | 2023-03-02T10:07:00 | 2023-03-02T10:07:00 | 222,457,383 | 102 | 106 | Apache-2.0 | false | 2023-07-22T21:56:12 | 2019-11-18T13:36:41 | 2023-07-19T05:45:36 | 2023-07-22T21:56:11 | 5,604 | 88 | 83 | 72 | Java | false | false | package org.openstack4j.api.network;
import java.util.ArrayList;
import java.util.List;
import org.openstack4j.api.AbstractTest;
import org.openstack4j.api.Builders;
import org.openstack4j.model.common.ActionResponse;
import org.openstack4j.model.network.Port;
import org.openstack4j.model.network.Trunk;
import org.openstack4j.model.network.TrunkSubport;
import org.openstack4j.openstack.networking.domain.NeutronTrunkSubport;
import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
/**
* Rewrote the entire API and so had to re-write tests
*
* @author Kashyap Jha
*/
@Test(suiteName = "Network")
public class TrunkTests extends AbstractTest {
private static final String JSON_CREATE_TRUNK_RESPONSE = "/network/createTrunkResponse.json";
private static final String JSON_ADD_SUBPORT_RESPONSE = "/network/addSubPortResponse.json";
private static final String JSON_REMOVE_SUBPORT_RESPONSE = "/network/removeSubPortResponse.json";
private static final String JSON_GET_TRUNK_RESPONSE = "/network/getTrunkResponse.json";
private static final String JSON_UPDATE_TRUNK_RESPONSE = "/network/updateTrunkResponse.json";
private static final String JSON_LIST_SUBPORTS_RESPONSE = "/network/listSubPortsResponse.json";
private static final String JSON_LIST_TRUNKS_RESPONSE = "/network/listTrunksResponse.json";
private static final String JSON_PORT_CREATE_RESPONSE = "/network/portCreateResponse.json";
@Override
protected Service service() {
return Service.NETWORK;
}
public void createTrunk() throws Exception {
respondWith(JSON_PORT_CREATE_RESPONSE);
String network1Id = "466e612-73a3-45df-96b6-4c084dfe1fc7";
String port1Name = "port1";
String trunk1Name = "trunk1";
Port toBuild = Builders.port().networkId(network1Id).name(port1Name).build();
Port builtPort = osv3().networking().port().create(toBuild);
respondWith(JSON_CREATE_TRUNK_RESPONSE);
Trunk builtTrunk = osv3.networking().trunk()
.create(Builders.neutron().trunk().name(trunk1Name).parentPort(builtPort.getId()).build());
assertNotNull(builtTrunk);
assertEquals(builtTrunk.getParentPort(), builtPort.getId());
assertEquals(builtTrunk.getName(), trunk1Name);
}
public void deleteTrunk() throws Exception {
respondWith(204);
String trunkId = "8a2ea42d-06b5-42c2-a54d-97105420f2bb";
ActionResponse delete = osv3().networking().trunk().delete(trunkId);
assertTrue(delete.isSuccess());
}
public void listTrunks() throws Exception {
respondWith(JSON_LIST_TRUNKS_RESPONSE);
String trunk1Id = "cf15956d-4391-4ebf-a9cb-0f7e27b24073";
String trunk2Id = "f98559e9-8e92-4100-96ac-a805e0340abd";
List<String> trunkIds = new ArrayList<>();
for (Trunk t : osv3().networking().trunk().list()) {
assertNotNull(t);
trunkIds.add(t.getId());
}
assertTrue(trunkIds.contains(trunk1Id));
assertTrue(trunkIds.contains(trunk2Id));
}
public void updateTrunk() throws Exception {
respondWith(JSON_UPDATE_TRUNK_RESPONSE);
String trunkId = "f98559e9-8e92-4100-96ac-a805e0340abd";
String updatedName = "changedName";
Trunk updatedTrunk = osv3().networking().trunk().update(Builders.neutron().trunk().trunkId(trunkId).name(updatedName).build());
assertNotNull(updatedTrunk);
assertEquals(updatedTrunk.getName(), updatedName);
assertEquals(updatedTrunk.getId(), trunkId);
}
public void addTrunkSubport() throws Exception {
respondWith(JSON_ADD_SUBPORT_RESPONSE);
String trunkId = "f98559e9-8e92-4100-96ac-a805e0340abd";
String subPortId = "9d30c4d8-3bb6-4b59-99ab-5eaa22e55037";
int segmentationId = 101;
String segmentationType = "vlan";
TrunkSubport subPort = NeutronTrunkSubport.builder().portId(subPortId).segmentationId(segmentationId)
.segmentationType("vlan").build();
Trunk withSubPort = osv3().networking().trunk().addTrunkSubport(trunkId, subPort);
assertNotNull(withSubPort);
assertEquals(subPortId, withSubPort.getTrunkSubports().get(0).getPortId());
assertEquals(segmentationId, withSubPort.getTrunkSubports().get(0).getSegmentationId());
assertEquals(segmentationType, withSubPort.getTrunkSubports().get(0).getSegmentationType());
}
public void removeTrunkSubport() throws Exception {
respondWith(JSON_REMOVE_SUBPORT_RESPONSE);
String trunkId = "f98559e9-8e92-4100-96ac-a805e0340abd";
String subPortId = "9d30c4d8-3bb6-4b59-99ab-5eaa22e55037";
Trunk withoutSubport = osv3().networking().trunk().removeTrunkSubport(trunkId, subPortId);
assertNotNull(withoutSubport);
assertTrue(withoutSubport.getTrunkSubports().isEmpty());
}
public void listTrunkSubports() throws Exception {
respondWith(JSON_LIST_SUBPORTS_RESPONSE);
String trunkId = "f98559e9-8e92-4100-96ac-a805e0340abd";
List<String> ids = new ArrayList<>();
List<NeutronTrunkSubport> subPorts = osv3().networking().trunk().listTrunkSubports(trunkId);
assertNotNull(subPorts);
for (TrunkSubport subPort : subPorts) {
assertNotNull(subPort);
ids.add(subPort.getId());
}
assertEquals(ids.size(), 2);
}
public void getTrunk() throws Exception {
respondWith(JSON_GET_TRUNK_RESPONSE);
String trunkId = "cf15956d-4391-4ebf-a9cb-0f7e27b24073";
String portId = "e2d70799-b1e3-4737-9298-23cfb5c94416";
Trunk trunk = osv3().networking().trunk().get(trunkId);
assertNotNull(trunk);
assertEquals(trunkId, trunk.getId());
assertEquals(portId, trunk.getParentPort());
}
}
| UTF-8 | Java | 5,985 | java | TrunkTests.java | Java | [
{
"context": "ire API and so had to re-write tests\n *\n * @author Kashyap Jha\n */\n@Test(suiteName = \"Network\")\npublic class Tru",
"end": 689,
"score": 0.9998463988304138,
"start": 678,
"tag": "NAME",
"value": "Kashyap Jha"
}
] | null | [] | package org.openstack4j.api.network;
import java.util.ArrayList;
import java.util.List;
import org.openstack4j.api.AbstractTest;
import org.openstack4j.api.Builders;
import org.openstack4j.model.common.ActionResponse;
import org.openstack4j.model.network.Port;
import org.openstack4j.model.network.Trunk;
import org.openstack4j.model.network.TrunkSubport;
import org.openstack4j.openstack.networking.domain.NeutronTrunkSubport;
import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
/**
* Rewrote the entire API and so had to re-write tests
*
* @author <NAME>
*/
@Test(suiteName = "Network")
public class TrunkTests extends AbstractTest {
private static final String JSON_CREATE_TRUNK_RESPONSE = "/network/createTrunkResponse.json";
private static final String JSON_ADD_SUBPORT_RESPONSE = "/network/addSubPortResponse.json";
private static final String JSON_REMOVE_SUBPORT_RESPONSE = "/network/removeSubPortResponse.json";
private static final String JSON_GET_TRUNK_RESPONSE = "/network/getTrunkResponse.json";
private static final String JSON_UPDATE_TRUNK_RESPONSE = "/network/updateTrunkResponse.json";
private static final String JSON_LIST_SUBPORTS_RESPONSE = "/network/listSubPortsResponse.json";
private static final String JSON_LIST_TRUNKS_RESPONSE = "/network/listTrunksResponse.json";
private static final String JSON_PORT_CREATE_RESPONSE = "/network/portCreateResponse.json";
@Override
protected Service service() {
return Service.NETWORK;
}
public void createTrunk() throws Exception {
respondWith(JSON_PORT_CREATE_RESPONSE);
String network1Id = "466e612-73a3-45df-96b6-4c084dfe1fc7";
String port1Name = "port1";
String trunk1Name = "trunk1";
Port toBuild = Builders.port().networkId(network1Id).name(port1Name).build();
Port builtPort = osv3().networking().port().create(toBuild);
respondWith(JSON_CREATE_TRUNK_RESPONSE);
Trunk builtTrunk = osv3.networking().trunk()
.create(Builders.neutron().trunk().name(trunk1Name).parentPort(builtPort.getId()).build());
assertNotNull(builtTrunk);
assertEquals(builtTrunk.getParentPort(), builtPort.getId());
assertEquals(builtTrunk.getName(), trunk1Name);
}
public void deleteTrunk() throws Exception {
respondWith(204);
String trunkId = "8a2ea42d-06b5-42c2-a54d-97105420f2bb";
ActionResponse delete = osv3().networking().trunk().delete(trunkId);
assertTrue(delete.isSuccess());
}
public void listTrunks() throws Exception {
respondWith(JSON_LIST_TRUNKS_RESPONSE);
String trunk1Id = "cf15956d-4391-4ebf-a9cb-0f7e27b24073";
String trunk2Id = "f98559e9-8e92-4100-96ac-a805e0340abd";
List<String> trunkIds = new ArrayList<>();
for (Trunk t : osv3().networking().trunk().list()) {
assertNotNull(t);
trunkIds.add(t.getId());
}
assertTrue(trunkIds.contains(trunk1Id));
assertTrue(trunkIds.contains(trunk2Id));
}
public void updateTrunk() throws Exception {
respondWith(JSON_UPDATE_TRUNK_RESPONSE);
String trunkId = "f98559e9-8e92-4100-96ac-a805e0340abd";
String updatedName = "changedName";
Trunk updatedTrunk = osv3().networking().trunk().update(Builders.neutron().trunk().trunkId(trunkId).name(updatedName).build());
assertNotNull(updatedTrunk);
assertEquals(updatedTrunk.getName(), updatedName);
assertEquals(updatedTrunk.getId(), trunkId);
}
public void addTrunkSubport() throws Exception {
respondWith(JSON_ADD_SUBPORT_RESPONSE);
String trunkId = "f98559e9-8e92-4100-96ac-a805e0340abd";
String subPortId = "9d30c4d8-3bb6-4b59-99ab-5eaa22e55037";
int segmentationId = 101;
String segmentationType = "vlan";
TrunkSubport subPort = NeutronTrunkSubport.builder().portId(subPortId).segmentationId(segmentationId)
.segmentationType("vlan").build();
Trunk withSubPort = osv3().networking().trunk().addTrunkSubport(trunkId, subPort);
assertNotNull(withSubPort);
assertEquals(subPortId, withSubPort.getTrunkSubports().get(0).getPortId());
assertEquals(segmentationId, withSubPort.getTrunkSubports().get(0).getSegmentationId());
assertEquals(segmentationType, withSubPort.getTrunkSubports().get(0).getSegmentationType());
}
public void removeTrunkSubport() throws Exception {
respondWith(JSON_REMOVE_SUBPORT_RESPONSE);
String trunkId = "f98559e9-8e92-4100-96ac-a805e0340abd";
String subPortId = "9d30c4d8-3bb6-4b59-99ab-5eaa22e55037";
Trunk withoutSubport = osv3().networking().trunk().removeTrunkSubport(trunkId, subPortId);
assertNotNull(withoutSubport);
assertTrue(withoutSubport.getTrunkSubports().isEmpty());
}
public void listTrunkSubports() throws Exception {
respondWith(JSON_LIST_SUBPORTS_RESPONSE);
String trunkId = "f98559e9-8e92-4100-96ac-a805e0340abd";
List<String> ids = new ArrayList<>();
List<NeutronTrunkSubport> subPorts = osv3().networking().trunk().listTrunkSubports(trunkId);
assertNotNull(subPorts);
for (TrunkSubport subPort : subPorts) {
assertNotNull(subPort);
ids.add(subPort.getId());
}
assertEquals(ids.size(), 2);
}
public void getTrunk() throws Exception {
respondWith(JSON_GET_TRUNK_RESPONSE);
String trunkId = "cf15956d-4391-4ebf-a9cb-0f7e27b24073";
String portId = "e2d70799-b1e3-4737-9298-23cfb5c94416";
Trunk trunk = osv3().networking().trunk().get(trunkId);
assertNotNull(trunk);
assertEquals(trunkId, trunk.getId());
assertEquals(portId, trunk.getParentPort());
}
}
| 5,980 | 0.698413 | 0.649123 | 142 | 41.147888 | 31.296616 | 135 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.683099 | false | false | 9 |
2d1c988e053e4324d07c2580906e0cb0effc97df | 1,047,972,065,253 | 8ec6ca4f534bfdfc3ff947e9621a9353c72be223 | /src/test/java/io/pivotal/function/ClearRegionClientTests.java | 32eba79d9efec3f61b6304f15376579d80cf8e9d | [
"BSD-3-Clause"
] | permissive | Pivotal-Data-Engineering/clear-partitioned-region | https://github.com/Pivotal-Data-Engineering/clear-partitioned-region | 23aeabeffa084d4ac81aa3767e01d3681cfe8782 | 83a4cbc149b334a578bd220922a7bee070c9782c | refs/heads/master | 2021-01-10T16:01:36.049000 | 2020-11-19T04:03:52 | 2020-11-19T04:03:52 | 44,325,009 | 1 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package io.pivotal.function;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.Set;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import com.gemstone.gemfire.cache.Region;
import com.gemstone.gemfire.cache.client.ClientCache;
import com.gemstone.gemfire.cache.client.ClientCacheFactory;
import com.gemstone.gemfire.cache.client.ClientRegionShortcut;
import com.gemstone.gemfire.cache.client.Pool;
import com.gemstone.gemfire.cache.client.PoolFactory;
import com.gemstone.gemfire.cache.client.PoolManager;
import com.gemstone.gemfire.cache.execute.Execution;
import com.gemstone.gemfire.cache.execute.FunctionService;
import com.gemstone.gemfire.cache.execute.ResultCollector;
import io.pivotal.collectors.MockResultCollector;
import io.pivotal.collectors.MockResultSender;
/**
* Unit test for simple App.
*/
public class ClearRegionClientTests
{
private static ClientCache clientCache;
private static MockResultSender<String> resultSender;
private static ResultCollector<Object, Object> resultCollector = new MockResultCollector<Object, Object>();
private static Pool pool;
private static Region pRegion = null;
private static Region<?, ?> rRegion = null;
Random r = new Random(new Date().getTime());
DateFormat df = new SimpleDateFormat("HH:mm:ss.SSS");
@BeforeClass
public static void init() {
clientCache = new ClientCacheFactory().set("name", "RegionCleaner").set("log-level", "error").create();
PoolFactory pf = PoolManager.createFactory();
pf.addLocator("localhost", 10334);
pool = pf.create("pool");
pRegion = clientCache.createClientRegionFactory(ClientRegionShortcut.PROXY).setPoolName("pool")
.create("pRegion");
rRegion = clientCache.createClientRegionFactory(ClientRegionShortcut.PROXY).setPoolName("pool")
.create("rRegion");
resultSender = new MockResultSender<String>();
}
/**
* Test clearing regions using regex. Create a few regions beginning with
* Test...
*/
@Test
public void testClearMultipleReplicatedRegions() {
System.out.println("Multiple Replicated Regions - Partitioned regions should fail");
String regionNamesString = "Test1,Test2,Test3,Test4,Test5,Test6";
String[] regionNames = regionNamesString.split(",");
for (String regionName : regionNames) {
long startTime = System.currentTimeMillis();
ResultCollector<String, List<String>> rc = callFunctionInParallelForReplicated(regionName, true);
List<String> result = rc.getResult();
for (int j = 0; j < result.size(); j++) {
if (result.get(j).trim().length() > 0) {
System.out.println(df.format(new Date()) + " - " + j + ": " + result.get(j) + ", elapsed=" + (System.currentTimeMillis() - startTime));
}
}
rc.clearResults();
}
System.out.println("***************************************************************");
}
/**
* Test clearing regions using regex. Create a few regions beginning with
* Test...
*/
@Test
public void testClearMultiplePartitionedRegions() {
System.out.println("Multiple Partitioned Regions - All should work");
String regionNamesString = "Test1,Test2,Test3,Test4,Test5,Test6";
String[] regionNames = regionNamesString.split(",");
for (String regionName : regionNames) {
long startTime = System.currentTimeMillis();
ResultCollector<String, List<String>> rc = callFunctionInParallel(regionName, true);
List<String> result = rc.getResult();
for (int j = 0; j < result.size(); j++) {
if (result.get(j).trim().length() > 0) {
System.out.println(df.format(new Date()) + " - " + j + ": " + result.get(j) + ", elapsed=" + (System.currentTimeMillis() - startTime));
}
}
rc.clearResults();
}
System.out.println("***************************************************************");
}
/**
* Test clearing regions without using regex
*/
@Test
public void testClearRegionInParallel() {
String regionName = "pRegion";
for (int i = 0; i < 10; i++) {
long startTime = System.currentTimeMillis();
ResultCollector<String, List<String>> rc = callFunctionInParallel(regionName, true);
List<String> result = rc.getResult();
for (int j = 0; j < result.size(); j++) {
if (result.get(j).trim().length() > 0) {
System.out.println(df.format(new Date()) + " " + i + " - " + j + ": " + result.get(j) + ", elapsed=" + (System.currentTimeMillis() - startTime));
}
}
rc.clearResults();
}
System.out.println("***************************************************************");
for (int i = 0; i < 10; i++) {
regionName = "rRegion";
long startTime = System.currentTimeMillis();
ResultCollector<String, List<String>> rc = callFunctionInParallel(regionName, true);
List<String> result = rc.getResult();
for (int j = 0; j < result.size(); j++) {
if (result.get(j).trim().length() > 0) {
System.out.println(df.format(new Date()) + " " + i + " - " + j + ": " + result.get(j) + ", elapsed=" + (System.currentTimeMillis() - startTime));
}
}
rc.clearResults();
}
System.out.println("***************************************************************");
}
private void callFunction(String[] regionNames) {
Execution execution = FunctionService.onServer(pool).withArgs("foo").withCollector(resultCollector);
execution.execute("ClearRegionFunction");
}
private int generateRandomEntries(Region<String, String> region) {
int numberOfEntries = generateRandomNumberOfEntries(region);
System.out.println("\n" + df.format(new Date()) + ": Request to delete " + numberOfEntries + " entries");
return numberOfEntries;
}
private ResultCollector<String, List<String>> callFunctionInParallel(String regionName,
boolean doGenerateRandomEntries) {
Region region = clientCache.getRegion(regionName);
if (region == null) {
region = clientCache.createClientRegionFactory(ClientRegionShortcut.PROXY).setPoolName("pool")
.create(regionName);
}
if (doGenerateRandomEntries) {
generateRandomEntries(region);
}
// Set<?> keys = region.keySetOnServer();
// Execution execution =
// FunctionService.onRegion(region).withFilter(keys).withArgs(regionName)
// .withCollector(resultCollector);
Execution execution = FunctionService.onRegion(region).withArgs(regionName).withCollector(resultCollector);
@SuppressWarnings("unchecked")
ResultCollector<String, List<String>> rc = (ResultCollector<String, List<String>>) execution
.execute("ClearRegionParallelFunction");
return rc;
}
private ResultCollector<String, List<String>> callFunctionInParallelForReplicated(String regionNameString,
boolean doGenerateRandomEntries) {
String[] regionNames;
if (regionNameString.contains(",")) {
regionNames = new String[1];
regionNames[0] = regionNameString;
} else {
regionNames = regionNameString.split(",");
}
for (String regionName : regionNames) {
Region region = clientCache.getRegion(regionName);
if (region == null) {
region = clientCache.createClientRegionFactory(ClientRegionShortcut.PROXY).setPoolName("pool")
.create(regionName);
}
if (doGenerateRandomEntries) {
generateRandomEntries(region);
}
}
// Set<?> keys = region.keySetOnServer();
// Execution execution =
// FunctionService.onRegion(region).withFilter(keys).withArgs(regionName)
// .withCollector(resultCollector);
Execution execution = FunctionService.onServer(pool).withArgs(regionNameString).withCollector(resultCollector);
@SuppressWarnings("unchecked")
ResultCollector<String, List<String>> rc = (ResultCollector<String, List<String>>) execution
.execute("ClearRegionParallelFunction");
return rc;
}
private int generateRandomNumberOfEntries(Region<String, String> region) {
int numberOfEntries = 10000; //r.nextInt(1500);
for (int i = 0; i < numberOfEntries; i++) {
region.put(String.valueOf(i), String.valueOf(i));
}
return numberOfEntries;
}
}
| UTF-8 | Java | 7,967 | java | ClearRegionClientTests.java | Java | [] | null | [] | package io.pivotal.function;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.Set;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import com.gemstone.gemfire.cache.Region;
import com.gemstone.gemfire.cache.client.ClientCache;
import com.gemstone.gemfire.cache.client.ClientCacheFactory;
import com.gemstone.gemfire.cache.client.ClientRegionShortcut;
import com.gemstone.gemfire.cache.client.Pool;
import com.gemstone.gemfire.cache.client.PoolFactory;
import com.gemstone.gemfire.cache.client.PoolManager;
import com.gemstone.gemfire.cache.execute.Execution;
import com.gemstone.gemfire.cache.execute.FunctionService;
import com.gemstone.gemfire.cache.execute.ResultCollector;
import io.pivotal.collectors.MockResultCollector;
import io.pivotal.collectors.MockResultSender;
/**
* Unit test for simple App.
*/
public class ClearRegionClientTests
{
private static ClientCache clientCache;
private static MockResultSender<String> resultSender;
private static ResultCollector<Object, Object> resultCollector = new MockResultCollector<Object, Object>();
private static Pool pool;
private static Region pRegion = null;
private static Region<?, ?> rRegion = null;
Random r = new Random(new Date().getTime());
DateFormat df = new SimpleDateFormat("HH:mm:ss.SSS");
@BeforeClass
public static void init() {
clientCache = new ClientCacheFactory().set("name", "RegionCleaner").set("log-level", "error").create();
PoolFactory pf = PoolManager.createFactory();
pf.addLocator("localhost", 10334);
pool = pf.create("pool");
pRegion = clientCache.createClientRegionFactory(ClientRegionShortcut.PROXY).setPoolName("pool")
.create("pRegion");
rRegion = clientCache.createClientRegionFactory(ClientRegionShortcut.PROXY).setPoolName("pool")
.create("rRegion");
resultSender = new MockResultSender<String>();
}
/**
* Test clearing regions using regex. Create a few regions beginning with
* Test...
*/
@Test
public void testClearMultipleReplicatedRegions() {
System.out.println("Multiple Replicated Regions - Partitioned regions should fail");
String regionNamesString = "Test1,Test2,Test3,Test4,Test5,Test6";
String[] regionNames = regionNamesString.split(",");
for (String regionName : regionNames) {
long startTime = System.currentTimeMillis();
ResultCollector<String, List<String>> rc = callFunctionInParallelForReplicated(regionName, true);
List<String> result = rc.getResult();
for (int j = 0; j < result.size(); j++) {
if (result.get(j).trim().length() > 0) {
System.out.println(df.format(new Date()) + " - " + j + ": " + result.get(j) + ", elapsed=" + (System.currentTimeMillis() - startTime));
}
}
rc.clearResults();
}
System.out.println("***************************************************************");
}
/**
* Test clearing regions using regex. Create a few regions beginning with
* Test...
*/
@Test
public void testClearMultiplePartitionedRegions() {
System.out.println("Multiple Partitioned Regions - All should work");
String regionNamesString = "Test1,Test2,Test3,Test4,Test5,Test6";
String[] regionNames = regionNamesString.split(",");
for (String regionName : regionNames) {
long startTime = System.currentTimeMillis();
ResultCollector<String, List<String>> rc = callFunctionInParallel(regionName, true);
List<String> result = rc.getResult();
for (int j = 0; j < result.size(); j++) {
if (result.get(j).trim().length() > 0) {
System.out.println(df.format(new Date()) + " - " + j + ": " + result.get(j) + ", elapsed=" + (System.currentTimeMillis() - startTime));
}
}
rc.clearResults();
}
System.out.println("***************************************************************");
}
/**
* Test clearing regions without using regex
*/
@Test
public void testClearRegionInParallel() {
String regionName = "pRegion";
for (int i = 0; i < 10; i++) {
long startTime = System.currentTimeMillis();
ResultCollector<String, List<String>> rc = callFunctionInParallel(regionName, true);
List<String> result = rc.getResult();
for (int j = 0; j < result.size(); j++) {
if (result.get(j).trim().length() > 0) {
System.out.println(df.format(new Date()) + " " + i + " - " + j + ": " + result.get(j) + ", elapsed=" + (System.currentTimeMillis() - startTime));
}
}
rc.clearResults();
}
System.out.println("***************************************************************");
for (int i = 0; i < 10; i++) {
regionName = "rRegion";
long startTime = System.currentTimeMillis();
ResultCollector<String, List<String>> rc = callFunctionInParallel(regionName, true);
List<String> result = rc.getResult();
for (int j = 0; j < result.size(); j++) {
if (result.get(j).trim().length() > 0) {
System.out.println(df.format(new Date()) + " " + i + " - " + j + ": " + result.get(j) + ", elapsed=" + (System.currentTimeMillis() - startTime));
}
}
rc.clearResults();
}
System.out.println("***************************************************************");
}
private void callFunction(String[] regionNames) {
Execution execution = FunctionService.onServer(pool).withArgs("foo").withCollector(resultCollector);
execution.execute("ClearRegionFunction");
}
private int generateRandomEntries(Region<String, String> region) {
int numberOfEntries = generateRandomNumberOfEntries(region);
System.out.println("\n" + df.format(new Date()) + ": Request to delete " + numberOfEntries + " entries");
return numberOfEntries;
}
private ResultCollector<String, List<String>> callFunctionInParallel(String regionName,
boolean doGenerateRandomEntries) {
Region region = clientCache.getRegion(regionName);
if (region == null) {
region = clientCache.createClientRegionFactory(ClientRegionShortcut.PROXY).setPoolName("pool")
.create(regionName);
}
if (doGenerateRandomEntries) {
generateRandomEntries(region);
}
// Set<?> keys = region.keySetOnServer();
// Execution execution =
// FunctionService.onRegion(region).withFilter(keys).withArgs(regionName)
// .withCollector(resultCollector);
Execution execution = FunctionService.onRegion(region).withArgs(regionName).withCollector(resultCollector);
@SuppressWarnings("unchecked")
ResultCollector<String, List<String>> rc = (ResultCollector<String, List<String>>) execution
.execute("ClearRegionParallelFunction");
return rc;
}
private ResultCollector<String, List<String>> callFunctionInParallelForReplicated(String regionNameString,
boolean doGenerateRandomEntries) {
String[] regionNames;
if (regionNameString.contains(",")) {
regionNames = new String[1];
regionNames[0] = regionNameString;
} else {
regionNames = regionNameString.split(",");
}
for (String regionName : regionNames) {
Region region = clientCache.getRegion(regionName);
if (region == null) {
region = clientCache.createClientRegionFactory(ClientRegionShortcut.PROXY).setPoolName("pool")
.create(regionName);
}
if (doGenerateRandomEntries) {
generateRandomEntries(region);
}
}
// Set<?> keys = region.keySetOnServer();
// Execution execution =
// FunctionService.onRegion(region).withFilter(keys).withArgs(regionName)
// .withCollector(resultCollector);
Execution execution = FunctionService.onServer(pool).withArgs(regionNameString).withCollector(resultCollector);
@SuppressWarnings("unchecked")
ResultCollector<String, List<String>> rc = (ResultCollector<String, List<String>>) execution
.execute("ClearRegionParallelFunction");
return rc;
}
private int generateRandomNumberOfEntries(Region<String, String> region) {
int numberOfEntries = 10000; //r.nextInt(1500);
for (int i = 0; i < numberOfEntries; i++) {
region.put(String.valueOf(i), String.valueOf(i));
}
return numberOfEntries;
}
}
| 7,967 | 0.692356 | 0.686959 | 211 | 36.758293 | 33.305756 | 150 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.469194 | false | false | 9 |
977c1a0af8cb4fed999d639495742e3ff4791de4 | 6,201,932,786,517 | a3c66f37f45d90cd9f43fd9f7379a1f87728069f | /app/src/main/java/com/lsc/mabel/materialdesign/MainActivity.java | 94678055145f94d5264f8947385b78f0fd6a66f1 | [] | no_license | Mabyta/Dise-o | https://github.com/Mabyta/Dise-o | 2fda657e61e23155fc0799d5672e323a8494c77b | ad1b900319c5d028f88ca742a02e2aed7447e1dd | refs/heads/master | 2020-04-01T11:46:26.082000 | 2018-10-15T20:26:40 | 2018-10-15T20:26:40 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.lsc.mabel.materialdesign;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
Boolean nuevoTema=false;
@Override
protected void onCreate(Bundle savedInstanceState) {
setTheme(R.style.MyTema);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void cambiar(View view){
Intent intent=new Intent(getApplicationContext(),ScrollingActivity.class);
intent.putExtra("nuevoTema",nuevoTema);
startActivity(intent);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
nuevoTema=extras.getBoolean("nuevoTema");
}
}
}
| UTF-8 | Java | 904 | java | MainActivity.java | Java | [] | null | [] | package com.lsc.mabel.materialdesign;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
Boolean nuevoTema=false;
@Override
protected void onCreate(Bundle savedInstanceState) {
setTheme(R.style.MyTema);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void cambiar(View view){
Intent intent=new Intent(getApplicationContext(),ScrollingActivity.class);
intent.putExtra("nuevoTema",nuevoTema);
startActivity(intent);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
nuevoTema=extras.getBoolean("nuevoTema");
}
}
}
| 904 | 0.699115 | 0.698009 | 28 | 31.285715 | 23.024611 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.642857 | false | false | 9 |
e5c3d0c18b711f1799dfb1d410c50cbfa55d906b | 25,812,753,468,054 | cf52b3064d536af626339ddd30b28c0b8e15aaee | /loginserver/src/main/java/org/l2junity/loginserver/network/LoginClient.java | 8517747f3953e8f3b830b785278b99035c483736 | [] | no_license | LegacyofAden/emu-ungp | https://github.com/LegacyofAden/emu-ungp | 7aaa7d9fd60698cb784d8c2c1eaaa20ef0a8d59b | b76dc91157e43d67f886b6926afd11b110ed5dce | refs/heads/master | 2021-01-01T18:21:03.529000 | 2017-04-08T23:08:37 | 2017-04-08T23:08:37 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.l2junity.loginserver.network;
import lombok.Getter;
import lombok.Setter;
import org.l2junity.commons.model.SessionInfo;
import org.l2junity.commons.network.Client;
import org.l2junity.commons.network.Connection;
import org.l2junity.loginserver.db.dto.Account;
import org.l2junity.loginserver.manager.KeyManager;
import org.l2junity.loginserver.network.crypt.LoginCrypt;
import org.l2junity.loginserver.network.crypt.ScrambledRSAKeyPair;
import org.l2junity.loginserver.network.packets.LoginServerPacket;
import org.l2junity.loginserver.network.packets.s2c.Init;
import javax.crypto.SecretKey;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicReference;
/**
* @author ANZO
* @since 05.04.2017
*/
public class LoginClient extends Client<LoginClient> {
private final AtomicReference<LoginClientState> state = new AtomicReference<>(LoginClientState.CONNECTED);
@Getter
private final ScrambledRSAKeyPair scrambledRSAKeyPair;
@Getter
@Setter
private Account account;
@Getter
@Setter
private SessionInfo sessionInfo;
private byte[] gameGuardData;
public LoginClient(Connection<LoginClient> connection) {
super(connection);
scrambledRSAKeyPair = KeyManager.getInstance().getRandomScrambledRSAKeyPair();
getConnection().setCipher(new LoginCrypt(this));
}
public boolean compareAndSetState(LoginClientState compare, LoginClientState set) {
return state.compareAndSet(compare, set);
}
public LoginClientState getState() {
return state.get();
}
@Override
protected void onOpen() {
byte[] key = KeyManager.getInstance().generateBlowfishKey().getEncoded();
getConnection().getCipher().setKey(key);
sendPacket(new Init(this, key));
}
public boolean checkGameGuardData(byte[] data) {
return Arrays.equals(gameGuardData, data);
}
public void setGameGuardData(byte[] data) {
gameGuardData = data;
}
public void sendPacket(LoginServerPacket packet) {
if (!isConnected() || packet == null) {
return;
}
getConnection().sendPackets(new LoginServerPacket[]{packet});
}
public String getHostAddress() {
if (isConnected()) {
return getConnection().getSocketAddress().getAddress().getHostAddress();
}
return "not connected";
}
public void closeForce() {
state.set(LoginClientState.CLOSED);
getConnection().sendAndClose(null);
}
public void close(LoginServerPacket packet) {
if (!isConnected()) {
return;
}
state.set(LoginClientState.CLOSED);
getConnection().sendAndClose(new LoginServerPacket[]{packet});
}
}
| UTF-8 | Java | 2,611 | java | LoginClient.java | Java | [
{
"context": "current.atomic.AtomicReference;\r\n\r\n/**\r\n * @author ANZO\r\n * @since 05.04.2017\r\n */\r\npublic class LoginCli",
"end": 724,
"score": 0.998885989189148,
"start": 720,
"tag": "USERNAME",
"value": "ANZO"
}
] | null | [] | package org.l2junity.loginserver.network;
import lombok.Getter;
import lombok.Setter;
import org.l2junity.commons.model.SessionInfo;
import org.l2junity.commons.network.Client;
import org.l2junity.commons.network.Connection;
import org.l2junity.loginserver.db.dto.Account;
import org.l2junity.loginserver.manager.KeyManager;
import org.l2junity.loginserver.network.crypt.LoginCrypt;
import org.l2junity.loginserver.network.crypt.ScrambledRSAKeyPair;
import org.l2junity.loginserver.network.packets.LoginServerPacket;
import org.l2junity.loginserver.network.packets.s2c.Init;
import javax.crypto.SecretKey;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicReference;
/**
* @author ANZO
* @since 05.04.2017
*/
public class LoginClient extends Client<LoginClient> {
private final AtomicReference<LoginClientState> state = new AtomicReference<>(LoginClientState.CONNECTED);
@Getter
private final ScrambledRSAKeyPair scrambledRSAKeyPair;
@Getter
@Setter
private Account account;
@Getter
@Setter
private SessionInfo sessionInfo;
private byte[] gameGuardData;
public LoginClient(Connection<LoginClient> connection) {
super(connection);
scrambledRSAKeyPair = KeyManager.getInstance().getRandomScrambledRSAKeyPair();
getConnection().setCipher(new LoginCrypt(this));
}
public boolean compareAndSetState(LoginClientState compare, LoginClientState set) {
return state.compareAndSet(compare, set);
}
public LoginClientState getState() {
return state.get();
}
@Override
protected void onOpen() {
byte[] key = KeyManager.getInstance().generateBlowfishKey().getEncoded();
getConnection().getCipher().setKey(key);
sendPacket(new Init(this, key));
}
public boolean checkGameGuardData(byte[] data) {
return Arrays.equals(gameGuardData, data);
}
public void setGameGuardData(byte[] data) {
gameGuardData = data;
}
public void sendPacket(LoginServerPacket packet) {
if (!isConnected() || packet == null) {
return;
}
getConnection().sendPackets(new LoginServerPacket[]{packet});
}
public String getHostAddress() {
if (isConnected()) {
return getConnection().getSocketAddress().getAddress().getHostAddress();
}
return "not connected";
}
public void closeForce() {
state.set(LoginClientState.CLOSED);
getConnection().sendAndClose(null);
}
public void close(LoginServerPacket packet) {
if (!isConnected()) {
return;
}
state.set(LoginClientState.CLOSED);
getConnection().sendAndClose(new LoginServerPacket[]{packet});
}
}
| 2,611 | 0.741861 | 0.734584 | 94 | 25.776596 | 24.978781 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.37234 | false | false | 9 |
9bd679c13cfedffb5cecdb4e4044523384427069 | 919,123,027,885 | f8f48be9516b416f4d5c2cd7c306345bb6e6c23e | /app/src/main/java/com/quandoo/restaurant/data/local/entity/Reservation.java | 0e059d330c8dce6ab0b8dfc38718b4e1c900bfd5 | [] | no_license | mobi-life/Quandoo-Restaurant | https://github.com/mobi-life/Quandoo-Restaurant | e06c449e132ee88b6c57dea799e145c47a1a41e7 | b9b5ec6fad1dcb089c35fcf1ac1c97e595c6d3ba | refs/heads/master | 2021-05-14T07:32:09.446000 | 2018-01-09T13:13:11 | 2018-01-09T13:13:11 | 116,267,977 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.quandoo.restaurant.data.local.entity;
import android.arch.persistence.room.ColumnInfo;
import android.arch.persistence.room.Entity;
import android.arch.persistence.room.PrimaryKey;
/**
* Created by Behzad on 1/1/2018.
*/
@Entity
public class Reservation {
@PrimaryKey(autoGenerate = true)
private long id;
@ColumnInfo(name = "table_no")
private int tableNo;
@ColumnInfo(name = "customer_id")
private long customerId;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public int getTableNo() {
return tableNo;
}
public void setTableNo(int tableNo) {
this.tableNo = tableNo;
}
public long getCustomerId() {
return customerId;
}
public void setCustomerId(long customerId) {
this.customerId = customerId;
}
}
| UTF-8 | Java | 881 | java | Reservation.java | Java | [
{
"context": "ch.persistence.room.PrimaryKey;\n\n/**\n * Created by Behzad on 1/1/2018.\n */\n\n@Entity\npublic class Reservatio",
"end": 219,
"score": 0.9625697731971741,
"start": 213,
"tag": "NAME",
"value": "Behzad"
}
] | null | [] | package com.quandoo.restaurant.data.local.entity;
import android.arch.persistence.room.ColumnInfo;
import android.arch.persistence.room.Entity;
import android.arch.persistence.room.PrimaryKey;
/**
* Created by Behzad on 1/1/2018.
*/
@Entity
public class Reservation {
@PrimaryKey(autoGenerate = true)
private long id;
@ColumnInfo(name = "table_no")
private int tableNo;
@ColumnInfo(name = "customer_id")
private long customerId;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public int getTableNo() {
return tableNo;
}
public void setTableNo(int tableNo) {
this.tableNo = tableNo;
}
public long getCustomerId() {
return customerId;
}
public void setCustomerId(long customerId) {
this.customerId = customerId;
}
}
| 881 | 0.645857 | 0.639047 | 46 | 18.152174 | 16.950012 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.282609 | false | false | 9 |
5499d4c6457d76b5a5626c9b2270b3909db4c8d9 | 919,123,026,626 | 7687449d0a2d11a9f5dbb61eac091a28312fd4ae | /chapter_001/src/main/java/ru/job4j/chess/Oficer.java | 0238bdcdc105eb0d8855f2101bc365507e6570e8 | [
"Apache-2.0"
] | permissive | ilyaVishnev/ilyav | https://github.com/ilyaVishnev/ilyav | b1d62c5dd1c3d58d89651521ee94fd0eda46c7d8 | a4a3e24dac576c229cc0ff60b3335b56ff81231f | refs/heads/master | 2018-11-10T04:45:48.510000 | 2018-08-31T01:35:50 | 2018-08-31T01:35:50 | 108,573,233 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ru.job4j.chess;
public class Oficer extends Figure {
public Oficer(Cell source) {
super(source);
}
public Cell[] way(Cell dist) throws ImposibleMoveException {
Cell[] way = new Cell[Math.abs(this.position.y - dist.y)];
if ((this.position.x - dist.x) == (this.position.y - dist.y)) {
for (int index = 0; index != way.length; index++) {
way[index] = new Cell(this.position.x + (index + 1) * ((dist.x - this.position.x) / Math.abs(this.position.x - dist.x)), this.position.y + (index + 1) * ((dist.y - this.position.y) / Math.abs(this.position.y - dist.y)));
}
} else if ((this.position.x - dist.x) == -1 * (this.position.y - dist.y)) {
for (int index = 0; index != way.length; index++) {
way[index] = new Cell(this.position.x + (index + 1) * ((dist.x - this.position.x) / Math.abs(this.position.x - dist.x)), this.position.y + (index + 1) * ((dist.y - this.position.y) / Math.abs(this.position.y - dist.y)));
}
} else {
throw new ImposibleMoveException();
}
return way;
}
public Figure clone(Cell dist){
return new Oficer(dist);
}
}
| UTF-8 | Java | 1,221 | java | Oficer.java | Java | [] | null | [] | package ru.job4j.chess;
public class Oficer extends Figure {
public Oficer(Cell source) {
super(source);
}
public Cell[] way(Cell dist) throws ImposibleMoveException {
Cell[] way = new Cell[Math.abs(this.position.y - dist.y)];
if ((this.position.x - dist.x) == (this.position.y - dist.y)) {
for (int index = 0; index != way.length; index++) {
way[index] = new Cell(this.position.x + (index + 1) * ((dist.x - this.position.x) / Math.abs(this.position.x - dist.x)), this.position.y + (index + 1) * ((dist.y - this.position.y) / Math.abs(this.position.y - dist.y)));
}
} else if ((this.position.x - dist.x) == -1 * (this.position.y - dist.y)) {
for (int index = 0; index != way.length; index++) {
way[index] = new Cell(this.position.x + (index + 1) * ((dist.x - this.position.x) / Math.abs(this.position.x - dist.x)), this.position.y + (index + 1) * ((dist.y - this.position.y) / Math.abs(this.position.y - dist.y)));
}
} else {
throw new ImposibleMoveException();
}
return way;
}
public Figure clone(Cell dist){
return new Oficer(dist);
}
}
| 1,221 | 0.555283 | 0.548731 | 26 | 45.96154 | 60.029148 | 236 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.538462 | false | false | 9 |
c062d3eb52a150e7f759ed68466cd4013ef63b28 | 10,385,230,948,259 | fd00e00bd35111e245ec778f1999bdb1ef02564b | /JsTestDriver/src/com/google/jstestdriver/idea/assertFramework/qunit/QUnitAdapterSupportInspection.java | 03eb823695858f4bad4689c6697245270cde017a | [
"Apache-2.0"
] | permissive | beyondeverljw/intellij-plugins | https://github.com/beyondeverljw/intellij-plugins | 8a5dc57da7131b4a1bae840b93e20df939dc9256 | f4f79b0fcf0a7c94fa3f824a4c3fb7c9d034ebf9 | refs/heads/master | 2019-03-21T00:38:17.702000 | 2018-03-05T15:45:29 | 2018-03-05T15:45:29 | 124,076,426 | 1 | 0 | null | true | 2018-03-06T12:38:30 | 2018-03-06T12:38:29 | 2018-03-05T16:31:24 | 2018-03-06T12:05:33 | 321,638 | 0 | 0 | 0 | null | false | null | package com.google.jstestdriver.idea.assertFramework.qunit;
import com.google.jstestdriver.idea.assertFramework.qunit.jsSrc.QUnitAdapterSrcMarker;
import com.google.jstestdriver.idea.assertFramework.support.AbstractAddAdapterSupportInspection;
import com.google.jstestdriver.idea.util.VfsUtils;
import com.intellij.javascript.testFramework.qunit.QUnitFileStructure;
import com.intellij.javascript.testFramework.qunit.QUnitFileStructureBuilder;
import com.intellij.lang.javascript.psi.JSCallExpression;
import com.intellij.lang.javascript.psi.JSFile;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.NotNullProducer;
import org.jetbrains.annotations.NotNull;
import java.util.List;
public class QUnitAdapterSupportInspection extends AbstractAddAdapterSupportInspection {
public QUnitAdapterSupportInspection() {
super(
"QUnit",
() -> {
String[] relativePaths = new String[]{"equiv.js", "QUnitAdapter.js"};
return VfsUtils.findVirtualFilesByResourceNames(QUnitAdapterSrcMarker.class, relativePaths);
},
"https://github.com/exnor/QUnit-to-JsTestDriver-adapter"
);
}
@Override
protected boolean isSuitableElement(@NotNull JSFile jsFile, @NotNull JSCallExpression callExpression) {
QUnitFileStructure structure = QUnitFileStructureBuilder.getInstance().fetchCachedTestFileStructure(jsFile);
String name = structure.getNameByPsiElement(callExpression);
return name != null;
}
}
| UTF-8 | Java | 1,469 | java | QUnitAdapterSupportInspection.java | Java | [
{
"context": "elativePaths);\n },\n \"https://github.com/exnor/QUnit-to-JsTestDriver-adapter\"\n );\n }\n\n @Ove",
"end": 1097,
"score": 0.9995202422142029,
"start": 1092,
"tag": "USERNAME",
"value": "exnor"
}
] | null | [] | package com.google.jstestdriver.idea.assertFramework.qunit;
import com.google.jstestdriver.idea.assertFramework.qunit.jsSrc.QUnitAdapterSrcMarker;
import com.google.jstestdriver.idea.assertFramework.support.AbstractAddAdapterSupportInspection;
import com.google.jstestdriver.idea.util.VfsUtils;
import com.intellij.javascript.testFramework.qunit.QUnitFileStructure;
import com.intellij.javascript.testFramework.qunit.QUnitFileStructureBuilder;
import com.intellij.lang.javascript.psi.JSCallExpression;
import com.intellij.lang.javascript.psi.JSFile;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.NotNullProducer;
import org.jetbrains.annotations.NotNull;
import java.util.List;
public class QUnitAdapterSupportInspection extends AbstractAddAdapterSupportInspection {
public QUnitAdapterSupportInspection() {
super(
"QUnit",
() -> {
String[] relativePaths = new String[]{"equiv.js", "QUnitAdapter.js"};
return VfsUtils.findVirtualFilesByResourceNames(QUnitAdapterSrcMarker.class, relativePaths);
},
"https://github.com/exnor/QUnit-to-JsTestDriver-adapter"
);
}
@Override
protected boolean isSuitableElement(@NotNull JSFile jsFile, @NotNull JSCallExpression callExpression) {
QUnitFileStructure structure = QUnitFileStructureBuilder.getInstance().fetchCachedTestFileStructure(jsFile);
String name = structure.getNameByPsiElement(callExpression);
return name != null;
}
}
| 1,469 | 0.800545 | 0.800545 | 36 | 39.805557 | 35.686771 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.638889 | false | false | 9 |
b6409fa3ea6da7ee6e2a5deda0b3a2409dae9c88 | 9,010,841,398,682 | 7447f3599a9d0f7d430b7402dde6dadbbfc0aba0 | /jbpm/superwifi/.svn/pristine/b6/b6409fa3ea6da7ee6e2a5deda0b3a2409dae9c88.svn-base | 793b56fde978a22307ed849e34f663d601d9110c | [] | no_license | liveqmock/workspace | https://github.com/liveqmock/workspace | 43d5ad79fc0f0675412829d9015cf68255f9d891 | c1da6eab74047cd612b1b3b1046c8fa03c5809fb | refs/heads/master | 2020-04-02T01:11:11.800000 | 2015-04-13T02:55:46 | 2015-04-13T02:55:46 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.yazuo.superwifi.security.vo;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import org.springframework.security.core.CredentialsContainer;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.SpringSecurityCoreVersion;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.Assert;
public class BaseUserDetails implements UserDetails, CredentialsContainer
{
private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
protected String password;
protected final String username;
protected final Set<GrantedAuthority> authorities;
protected final boolean accountNonExpired;
protected final boolean accountNonLocked;
protected final boolean credentialsNonExpired;
protected final boolean enabled;
public BaseUserDetails(String username, String password,
Collection<? extends GrantedAuthority> authorities)
{
this(username, password, true, true, true, true, authorities);
}
public BaseUserDetails(String username, String password, boolean enabled,
boolean accountNonExpired, boolean credentialsNonExpired,
boolean accountNonLocked,
Collection<? extends GrantedAuthority> authorities)
{
if (((username == null) || "".equals(username)) || (password == null))
{
throw new IllegalArgumentException("Cannot pass null or empty values to constructor");
}
this.username = username;
this.password = password;
this.enabled = enabled;
this.accountNonExpired = accountNonExpired;
this.credentialsNonExpired = credentialsNonExpired;
this.accountNonLocked = accountNonLocked;
this.authorities = Collections.unmodifiableSet(sortAuthorities(authorities));
}
public Collection<GrantedAuthority> getAuthorities()
{
return authorities;
}
public Collection<String> getStringAuthorities()
{
Collection<String> stringAuthorities=new ArrayList<String>();
for(GrantedAuthority ga:authorities){
stringAuthorities.add(ga.toString());
}
return stringAuthorities;
}
public String getPassword()
{
return password;
}
public String getUsername()
{
return username;
}
public boolean isEnabled()
{
return enabled;
}
public boolean isAccountNonExpired()
{
return accountNonExpired;
}
public boolean isAccountNonLocked()
{
return accountNonLocked;
}
public boolean isCredentialsNonExpired()
{
return credentialsNonExpired;
}
public void eraseCredentials()
{
password = null;
}
private static SortedSet<GrantedAuthority> sortAuthorities(Collection<? extends GrantedAuthority> authorities)
{
Assert.notNull(authorities, "Cannot pass a null GrantedAuthority collection");
SortedSet<GrantedAuthority> sortedAuthorities = new TreeSet<GrantedAuthority>(
new AuthorityComparator());
for (GrantedAuthority grantedAuthority : authorities)
{
Assert.notNull(grantedAuthority,
"GrantedAuthority list cannot contain any null elements");
sortedAuthorities.add(grantedAuthority);
}
return sortedAuthorities;
}
private static class AuthorityComparator implements Comparator<GrantedAuthority>, Serializable
{
private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
public int compare(GrantedAuthority g1, GrantedAuthority g2)
{
if (g2.getAuthority() == null)
{
return -1;
}
if (g1.getAuthority() == null)
{
return 1;
}
return g1.getAuthority().compareTo(g2.getAuthority());
}
}
@Override
public boolean equals(Object rhs)
{
if (rhs instanceof User)
{
return username.equals(((BaseUserDetails)rhs).username);
}
return false;
}
@Override
public int hashCode()
{
return username.hashCode();
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append(super.toString()).append(": ");
sb.append("Username: ").append(this.username).append("; ");
sb.append("Password: [PROTECTED]; ");
sb.append("Enabled: ").append(this.enabled).append("; ");
sb.append("AccountNonExpired: ").append(this.accountNonExpired).append("; ");
sb.append("credentialsNonExpired: ").append(this.credentialsNonExpired).append("; ");
sb.append("AccountNonLocked: ").append(this.accountNonLocked).append("; ");
if (!authorities.isEmpty())
{
sb.append("Granted Authorities: ");
boolean first = true;
for (GrantedAuthority auth : authorities)
{
if (!first)
{
sb.append(",");
}
first = false;
sb.append(auth);
}
}
else
{
sb.append("Not granted any authorities");
}
return sb.toString();
}
}
| UTF-8 | Java | 5,915 | b6409fa3ea6da7ee6e2a5deda0b3a2409dae9c88.svn-base | Java | [
{
"context": "nstructor\");\r\n }\r\n\r\n this.username = username;\r\n this.password = password;\r\n this",
"end": 1917,
"score": 0.996921956539154,
"start": 1909,
"tag": "USERNAME",
"value": "username"
},
{
"context": "this.username = username;\r\n this.password = password;\r\n this.enabled = enabled;\r\n this.a",
"end": 1952,
"score": 0.9991143345832825,
"start": 1944,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "public String getPassword()\r\n {\r\n return password;\r\n }\r\n\r\n public String getUsername()\r\n {",
"end": 2704,
"score": 0.8311270475387573,
"start": 2696,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "public String getUsername()\r\n {\r\n return username;\r\n }\r\n\r\n public boolean isEnabled()\r\n {\r",
"end": 2779,
"score": 0.989437460899353,
"start": 2771,
"tag": "USERNAME",
"value": "username"
},
{
"context": "void eraseCredentials()\r\n {\r\n password = null;\r\n }\r\n\r\n private static SortedSet<GrantedAu",
"end": 3215,
"score": 0.8303799033164978,
"start": 3211,
"tag": "PASSWORD",
"value": "null"
}
] | null | [] | package com.yazuo.superwifi.security.vo;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import org.springframework.security.core.CredentialsContainer;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.SpringSecurityCoreVersion;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.Assert;
public class BaseUserDetails implements UserDetails, CredentialsContainer
{
private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
protected String password;
protected final String username;
protected final Set<GrantedAuthority> authorities;
protected final boolean accountNonExpired;
protected final boolean accountNonLocked;
protected final boolean credentialsNonExpired;
protected final boolean enabled;
public BaseUserDetails(String username, String password,
Collection<? extends GrantedAuthority> authorities)
{
this(username, password, true, true, true, true, authorities);
}
public BaseUserDetails(String username, String password, boolean enabled,
boolean accountNonExpired, boolean credentialsNonExpired,
boolean accountNonLocked,
Collection<? extends GrantedAuthority> authorities)
{
if (((username == null) || "".equals(username)) || (password == null))
{
throw new IllegalArgumentException("Cannot pass null or empty values to constructor");
}
this.username = username;
this.password = <PASSWORD>;
this.enabled = enabled;
this.accountNonExpired = accountNonExpired;
this.credentialsNonExpired = credentialsNonExpired;
this.accountNonLocked = accountNonLocked;
this.authorities = Collections.unmodifiableSet(sortAuthorities(authorities));
}
public Collection<GrantedAuthority> getAuthorities()
{
return authorities;
}
public Collection<String> getStringAuthorities()
{
Collection<String> stringAuthorities=new ArrayList<String>();
for(GrantedAuthority ga:authorities){
stringAuthorities.add(ga.toString());
}
return stringAuthorities;
}
public String getPassword()
{
return <PASSWORD>;
}
public String getUsername()
{
return username;
}
public boolean isEnabled()
{
return enabled;
}
public boolean isAccountNonExpired()
{
return accountNonExpired;
}
public boolean isAccountNonLocked()
{
return accountNonLocked;
}
public boolean isCredentialsNonExpired()
{
return credentialsNonExpired;
}
public void eraseCredentials()
{
password = <PASSWORD>;
}
private static SortedSet<GrantedAuthority> sortAuthorities(Collection<? extends GrantedAuthority> authorities)
{
Assert.notNull(authorities, "Cannot pass a null GrantedAuthority collection");
SortedSet<GrantedAuthority> sortedAuthorities = new TreeSet<GrantedAuthority>(
new AuthorityComparator());
for (GrantedAuthority grantedAuthority : authorities)
{
Assert.notNull(grantedAuthority,
"GrantedAuthority list cannot contain any null elements");
sortedAuthorities.add(grantedAuthority);
}
return sortedAuthorities;
}
private static class AuthorityComparator implements Comparator<GrantedAuthority>, Serializable
{
private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
public int compare(GrantedAuthority g1, GrantedAuthority g2)
{
if (g2.getAuthority() == null)
{
return -1;
}
if (g1.getAuthority() == null)
{
return 1;
}
return g1.getAuthority().compareTo(g2.getAuthority());
}
}
@Override
public boolean equals(Object rhs)
{
if (rhs instanceof User)
{
return username.equals(((BaseUserDetails)rhs).username);
}
return false;
}
@Override
public int hashCode()
{
return username.hashCode();
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append(super.toString()).append(": ");
sb.append("Username: ").append(this.username).append("; ");
sb.append("Password: [PROTECTED]; ");
sb.append("Enabled: ").append(this.enabled).append("; ");
sb.append("AccountNonExpired: ").append(this.accountNonExpired).append("; ");
sb.append("credentialsNonExpired: ").append(this.credentialsNonExpired).append("; ");
sb.append("AccountNonLocked: ").append(this.accountNonLocked).append("; ");
if (!authorities.isEmpty())
{
sb.append("Granted Authorities: ");
boolean first = true;
for (GrantedAuthority auth : authorities)
{
if (!first)
{
sb.append(",");
}
first = false;
sb.append(auth);
}
}
else
{
sb.append("Not granted any authorities");
}
return sb.toString();
}
}
| 5,925 | 0.610482 | 0.609129 | 201 | 27.42786 | 27.415108 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.497512 | false | false | 9 |
|
8d524d5cf55cfbb839ff42744d5824f9820db659 | 27,582,279,991,452 | a2a69febe8df9eac2df59b7921f21bacdd5cde72 | /src/main/java/fontysin/project/controllers/Util.java | 84f96318de16e6f06ae9e36043274ea63fd27247 | [] | no_license | yourivdloo/gps-fontysin | https://github.com/yourivdloo/gps-fontysin | 0134455e987a9834aed24f547b1db6f0be87ec8f | 8364dd9c26bb5aa995d946d2d80b52528ad3a893 | refs/heads/master | 2023-06-02T22:15:34.904000 | 2021-01-21T14:33:50 | 2021-01-21T14:34:35 | 378,521,416 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package fontysin.project.controllers;
import fontysin.project.exceptions.InternalServerException;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import static java.lang.Integer.parseInt;
public class Util {
private Util() {
throw new IllegalStateException("Cannot instantiate Utility Class");
}
public static int getPcn() {
try {
return parseInt(getEmail().split("@")[0]);
}
catch (Exception ex) {
throw new InternalServerException("Unable to parse PCN");
}
}
public static boolean isStudent() {
return getEmail().contains("@student.");
}
public static boolean emptyOrNull(String[] list) {
for (String input : list)
if (input == null || input.isEmpty()) {
return true;
}
return false;
}
public static boolean emptyOrNull(String input) {
return input == null || input.isEmpty();
}
private static String getEmail() {
ServletRequestAttributes attrib = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
assert attrib != null;
HttpServletRequest request = attrib.getRequest();
return request.getHeader("x-ms-client-principal-name");
}
}
| UTF-8 | Java | 1,421 | java | Util.java | Java | [] | null | [] | package fontysin.project.controllers;
import fontysin.project.exceptions.InternalServerException;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import static java.lang.Integer.parseInt;
public class Util {
private Util() {
throw new IllegalStateException("Cannot instantiate Utility Class");
}
public static int getPcn() {
try {
return parseInt(getEmail().split("@")[0]);
}
catch (Exception ex) {
throw new InternalServerException("Unable to parse PCN");
}
}
public static boolean isStudent() {
return getEmail().contains("@student.");
}
public static boolean emptyOrNull(String[] list) {
for (String input : list)
if (input == null || input.isEmpty()) {
return true;
}
return false;
}
public static boolean emptyOrNull(String input) {
return input == null || input.isEmpty();
}
private static String getEmail() {
ServletRequestAttributes attrib = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
assert attrib != null;
HttpServletRequest request = attrib.getRequest();
return request.getHeader("x-ms-client-principal-name");
}
}
| 1,421 | 0.658691 | 0.657987 | 48 | 28.604166 | 26.995169 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4375 | false | false | 9 |
ad1255330a388164bb39836bad98f7c8ec01f31d | 6,605,659,752,469 | 05d81646ba6f0dad7b2ea5fe068b3297e2cb2c7a | /PetboxShop/app/src/main/java/com/petbox/shop/Fragment/MyPage/MyPageCouponList.java | 4adb7d8e1986b0411f37eedaa7b2dcb33e98cdf5 | [] | no_license | HM-Jang/PETBOX_ANDR | https://github.com/HM-Jang/PETBOX_ANDR | c649ab7e08d142670c38efd987d0922ffafdfba3 | 35b3518ba5f3018af24e5b4438698e2ff2c2c3ad | refs/heads/master | 2021-01-10T17:42:48.473000 | 2015-10-18T11:30:36 | 2015-10-18T11:30:36 | 44,353,801 | 0 | 0 | null | false | 2015-10-26T00:23:48 | 2015-10-16T00:52:20 | 2015-10-16T00:53:17 | 2015-10-26T00:23:41 | 5,088 | 0 | 0 | 2 | Java | null | null | package com.petbox.shop.Fragment.MyPage;
import android.annotation.TargetApi;
import android.app.Activity;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.petbox.shop.Adapter.List.CouponListAdapter;
import com.petbox.shop.Adapter.List.EmoneyListAdapter;
import com.petbox.shop.Adapter.List.OrderListAdapter;
import com.petbox.shop.Delegate.MyPageDelegate;
import com.petbox.shop.Item.CouponInfo;
import com.petbox.shop.Item.EmoneyInfo;
import com.petbox.shop.Item.OrderItemInfo;
import com.petbox.shop.JsonParse;
import com.petbox.shop.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.ExecutionException;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link MyPageCouponList.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link MyPageCouponList#newInstance} factory method to
* create an instance of this fragment.
*/
public class MyPageCouponList extends Fragment implements View.OnClickListener {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
TextView tv_mypage_coupon_extinc,tv_mypage_coupon;
EditText et_coupon_insert1,et_coupon_insert2,et_coupon_insert3,et_coupon_insert4;
Button bt_coupon_reg,bt_go_home;
ListView lv_coupon_list;
ScrollView coupon_scroll;
CouponListAdapter listAdapter;
ArrayList<CouponInfo> mItemList;
String coupon_list;
String url,params3,InsertDB;
MyPageDelegate delegate;
private PullToRefreshListView listView;
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param2 Parameter 2.
* @return A new instance of fragment MyPageCouponList.
*/
// TODO: Rename and change types and number of parameters
public static MyPageCouponList newInstance(MyPageDelegate delegate, String param2) {
MyPageCouponList fragment = new MyPageCouponList();
Bundle args = new Bundle();
fragment.delegate = delegate;
//args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public MyPageCouponList() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@TargetApi(Build.VERSION_CODES.M)
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_my_page_coupon_list, container, false);
Log.e("--coupon fragment--", "inda club ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
tv_mypage_coupon_extinc = (TextView) v.findViewById(R.id.tv_mypage_coupon_extinc);
tv_mypage_coupon = (TextView) v.findViewById(R.id.tv_mypage_coupon);
et_coupon_insert1 = (EditText) v.findViewById(R.id.et_coupon_insert1);
et_coupon_insert2 = (EditText) v.findViewById(R.id.et_coupon_insert2);
et_coupon_insert3 = (EditText) v.findViewById(R.id.et_coupon_insert3);
et_coupon_insert4 = (EditText) v.findViewById(R.id.et_coupon_insert4);
bt_coupon_reg = (Button) v.findViewById(R.id.bt_coupon_reg);
bt_go_home = (Button) v.findViewById(R.id.bt_go_home);
lv_coupon_list = (ListView) v.findViewById(R.id.lv_coupon_list);
int cancoupon = 0;
int edt_coupon = 0;
String edt_coupon_mult="";
try {
String sno = "";
String coupon_name = "";
String coupon_type = "";
String coupon_price = "";
String status = "";
String sdate = "";
String edate = "";
url = "http://petbox.kr/petboxjson/member_info.php";
params3 = "?m_no=" + 1;
params3 += "&mypage_info=" + 804;
InsertDB = "mypage_coupon_list";
cancoupon = 0;
coupon_list = new JsonParse.JsonLoadingTask(getActivity().getApplicationContext()).execute(url, params3, InsertDB).get();
Log.e("order_list", coupon_list);
JSONArray CouponListArray = new JSONArray(coupon_list);
mItemList = new ArrayList<CouponInfo>();
CouponInfo info[] = new CouponInfo[CouponListArray.length()];
for (int k = 0; k < CouponListArray.length(); k++) {
JSONObject Coupon_object = CouponListArray.getJSONObject(k);
info[k] = new CouponInfo(sno, coupon_name, coupon_type, coupon_price, status, sdate, edate);
info[k].sno = Coupon_object.getString("sno");
info[k].coupon_name = Coupon_object.getString("coupon");
info[k].coupon_type = Coupon_object.getString("coupon_type");
info[k].coupon_price = Coupon_object.getString("coupon_price");
info[k].status = Coupon_object.getString("cnt");
info[k].sdate = Coupon_object.getString("sdate");
info[k].edate = Coupon_object.getString("edate");
if (Coupon_object.getInt("cnt") == 2) {
cancoupon++;
if(Coupon_object.getInt("remain_date") < 30){
edt_coupon++;
}
}
mItemList.add(info[k]);
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
Log.e("Cancoiupon", String.valueOf(cancoupon));
tv_mypage_coupon.setText(String.valueOf(cancoupon));
tv_mypage_coupon_extinc.setText(String.valueOf(edt_coupon));
listAdapter = new CouponListAdapter(getContext(), mItemList);
lv_coupon_list.setAdapter(listAdapter);
// Inflate the layout for this fragment
return v;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
@Override
public void onClick(View v) {
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
} | UTF-8 | Java | 8,338 | java | MyPageCouponList.java | Java | [] | null | [] | package com.petbox.shop.Fragment.MyPage;
import android.annotation.TargetApi;
import android.app.Activity;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.petbox.shop.Adapter.List.CouponListAdapter;
import com.petbox.shop.Adapter.List.EmoneyListAdapter;
import com.petbox.shop.Adapter.List.OrderListAdapter;
import com.petbox.shop.Delegate.MyPageDelegate;
import com.petbox.shop.Item.CouponInfo;
import com.petbox.shop.Item.EmoneyInfo;
import com.petbox.shop.Item.OrderItemInfo;
import com.petbox.shop.JsonParse;
import com.petbox.shop.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.ExecutionException;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link MyPageCouponList.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link MyPageCouponList#newInstance} factory method to
* create an instance of this fragment.
*/
public class MyPageCouponList extends Fragment implements View.OnClickListener {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
TextView tv_mypage_coupon_extinc,tv_mypage_coupon;
EditText et_coupon_insert1,et_coupon_insert2,et_coupon_insert3,et_coupon_insert4;
Button bt_coupon_reg,bt_go_home;
ListView lv_coupon_list;
ScrollView coupon_scroll;
CouponListAdapter listAdapter;
ArrayList<CouponInfo> mItemList;
String coupon_list;
String url,params3,InsertDB;
MyPageDelegate delegate;
private PullToRefreshListView listView;
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param2 Parameter 2.
* @return A new instance of fragment MyPageCouponList.
*/
// TODO: Rename and change types and number of parameters
public static MyPageCouponList newInstance(MyPageDelegate delegate, String param2) {
MyPageCouponList fragment = new MyPageCouponList();
Bundle args = new Bundle();
fragment.delegate = delegate;
//args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public MyPageCouponList() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@TargetApi(Build.VERSION_CODES.M)
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_my_page_coupon_list, container, false);
Log.e("--coupon fragment--", "inda club ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
tv_mypage_coupon_extinc = (TextView) v.findViewById(R.id.tv_mypage_coupon_extinc);
tv_mypage_coupon = (TextView) v.findViewById(R.id.tv_mypage_coupon);
et_coupon_insert1 = (EditText) v.findViewById(R.id.et_coupon_insert1);
et_coupon_insert2 = (EditText) v.findViewById(R.id.et_coupon_insert2);
et_coupon_insert3 = (EditText) v.findViewById(R.id.et_coupon_insert3);
et_coupon_insert4 = (EditText) v.findViewById(R.id.et_coupon_insert4);
bt_coupon_reg = (Button) v.findViewById(R.id.bt_coupon_reg);
bt_go_home = (Button) v.findViewById(R.id.bt_go_home);
lv_coupon_list = (ListView) v.findViewById(R.id.lv_coupon_list);
int cancoupon = 0;
int edt_coupon = 0;
String edt_coupon_mult="";
try {
String sno = "";
String coupon_name = "";
String coupon_type = "";
String coupon_price = "";
String status = "";
String sdate = "";
String edate = "";
url = "http://petbox.kr/petboxjson/member_info.php";
params3 = "?m_no=" + 1;
params3 += "&mypage_info=" + 804;
InsertDB = "mypage_coupon_list";
cancoupon = 0;
coupon_list = new JsonParse.JsonLoadingTask(getActivity().getApplicationContext()).execute(url, params3, InsertDB).get();
Log.e("order_list", coupon_list);
JSONArray CouponListArray = new JSONArray(coupon_list);
mItemList = new ArrayList<CouponInfo>();
CouponInfo info[] = new CouponInfo[CouponListArray.length()];
for (int k = 0; k < CouponListArray.length(); k++) {
JSONObject Coupon_object = CouponListArray.getJSONObject(k);
info[k] = new CouponInfo(sno, coupon_name, coupon_type, coupon_price, status, sdate, edate);
info[k].sno = Coupon_object.getString("sno");
info[k].coupon_name = Coupon_object.getString("coupon");
info[k].coupon_type = Coupon_object.getString("coupon_type");
info[k].coupon_price = Coupon_object.getString("coupon_price");
info[k].status = Coupon_object.getString("cnt");
info[k].sdate = Coupon_object.getString("sdate");
info[k].edate = Coupon_object.getString("edate");
if (Coupon_object.getInt("cnt") == 2) {
cancoupon++;
if(Coupon_object.getInt("remain_date") < 30){
edt_coupon++;
}
}
mItemList.add(info[k]);
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
Log.e("Cancoiupon", String.valueOf(cancoupon));
tv_mypage_coupon.setText(String.valueOf(cancoupon));
tv_mypage_coupon_extinc.setText(String.valueOf(edt_coupon));
listAdapter = new CouponListAdapter(getContext(), mItemList);
lv_coupon_list.setAdapter(listAdapter);
// Inflate the layout for this fragment
return v;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
@Override
public void onClick(View v) {
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
} | 8,338 | 0.651475 | 0.646078 | 233 | 34.7897 | 26.645559 | 133 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.643777 | false | false | 9 |
58af36ca0f3ac69f36ede0eedf60a0a97701bf8c | 6,141,803,239,910 | b32c2d10aea07e4a313c7a09d9be409acac58bdd | /ChatSoft/Server/ServerConnectionProtocolThread.java | 47aedb19003f4857467f249d19b95bcd734c9785 | [] | no_license | jduser/simple_chat_program_in_java | https://github.com/jduser/simple_chat_program_in_java | 1e4ab1d813eb21e3c106a3a8ba86fb088ad6d603 | d715c196278d8708db5dc43a04c5c24a053a7626 | refs/heads/master | 2015-08-11T00:52:57.800000 | 2014-03-30T04:06:30 | 2014-03-30T04:06:30 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.io.*;
import java.net.*;
import java.util.*;
public class ServerConnectionProtocolThread extends Thread {
Vector<SocketInfo> sl = null;
Socket s = null;
ServerMain sm = null;
ServerConnectionProtocolThread(Vector<SocketInfo> sl, Socket s, ServerMain sm) {
this.sl = sl;
this.s = s;
this.sm = sm;
}
public void run() {
try{
BufferedReader in = null;
PrintWriter out = null;
in = new BufferedReader(new InputStreamReader(s.getInputStream()));
out = new PrintWriter(s.getOutputStream(), true);
String name = in.readLine();
int found = 1;
while ((found=findName(name)) == 1) {
out.println("ERROR 1");
name = in.readLine();
}
out.println("EXIT");
int j = 0;
int size = sl.size();
while(j < size) {
String userId = sl.get(j).getName();
out.println("ADD:"+userId);
j++;
}
SocketInfo si = new SocketInfo(name, s);
sl.add(si);
sm.add(name);
new ServerRecieverThread(sl, si, sm).start();
}
catch (IOException e) {
}
catch (NullPointerException e) {
}
}
public int findName(String name) {
int i = 0;
int size = sl.size();
int found = 0;
while (i < size && found == 0) {
String temp = sl.get(i).getName();
if (temp.equals(name)) {
found = 1;
}
i++;
}
return found;
}
} | UTF-8 | Java | 1,380 | java | ServerConnectionProtocolThread.java | Java | [] | null | [] | import java.io.*;
import java.net.*;
import java.util.*;
public class ServerConnectionProtocolThread extends Thread {
Vector<SocketInfo> sl = null;
Socket s = null;
ServerMain sm = null;
ServerConnectionProtocolThread(Vector<SocketInfo> sl, Socket s, ServerMain sm) {
this.sl = sl;
this.s = s;
this.sm = sm;
}
public void run() {
try{
BufferedReader in = null;
PrintWriter out = null;
in = new BufferedReader(new InputStreamReader(s.getInputStream()));
out = new PrintWriter(s.getOutputStream(), true);
String name = in.readLine();
int found = 1;
while ((found=findName(name)) == 1) {
out.println("ERROR 1");
name = in.readLine();
}
out.println("EXIT");
int j = 0;
int size = sl.size();
while(j < size) {
String userId = sl.get(j).getName();
out.println("ADD:"+userId);
j++;
}
SocketInfo si = new SocketInfo(name, s);
sl.add(si);
sm.add(name);
new ServerRecieverThread(sl, si, sm).start();
}
catch (IOException e) {
}
catch (NullPointerException e) {
}
}
public int findName(String name) {
int i = 0;
int size = sl.size();
int found = 0;
while (i < size && found == 0) {
String temp = sl.get(i).getName();
if (temp.equals(name)) {
found = 1;
}
i++;
}
return found;
}
} | 1,380 | 0.576087 | 0.57029 | 78 | 16.705128 | 16.944941 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.935897 | false | false | 9 |
38baf25f41372eaaca4639b1c33e32ad0368152b | 704,374,685,548 | 68a433176f5aa328eb3fac36aece06f1e2fdaaf4 | /app/src/main/java/br/com/interaje/easytrade/repositories/impl/CarrinhoDAOImpl.java | 483058d64672b4d7af1db6ca023feebd77665be8 | [] | no_license | CharlesMiranda/EasyTrade | https://github.com/CharlesMiranda/EasyTrade | bf3042993b12bccc0841cbcb4ad3936910f14464 | 8c051609b6af651434f5e40ea2ab5400c490214d | refs/heads/master | 2021-01-10T18:14:21.577000 | 2016-02-25T13:20:00 | 2016-02-25T13:20:00 | 47,921,616 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.com.interaje.easytrade.repositories.impl;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;
import java.util.ArrayList;
import br.com.interaje.easytrade.database.CarrinhoDatabase;
import br.com.interaje.easytrade.database.CarrinhoDatabaseHelper;
import br.com.interaje.easytrade.model.Carrinho;
import br.com.interaje.easytrade.model.Produto;
import br.com.interaje.easytrade.repositories.CarrinhoDAO;
/**
* Created by charles on 21/11/15.
*/
public class CarrinhoDAOImpl implements CarrinhoDAO {
private String tableDAO = "carrinho";
/**
* Inserir
*/
@Override
public boolean salvar(Carrinho carrinho, CarrinhoDatabase carrinhoDatabase) {
ContentValues cv = new ContentValues();
carrinhoDatabase.open();
try {
if (carrinho != null) {
cv.put(CarrinhoDatabaseHelper.COLUMN_PRODUTO, carrinho.getProduto_id());
carrinhoDatabase.get().insert(tableDAO, null, cv);
}
} catch (Exception e) {
Log.d("CarrinhoDAOImpl",
"Method: salvar().\nErro ao inserir dados do banco. Causa: "
+ e.getCause());
carrinhoDatabase.close();
return false;
}
carrinhoDatabase.close();
return true;
}
/**
* Listar todos
*/
@Override
public ArrayList<Carrinho> find(Context context, CarrinhoDatabase carrinhoDatabase, String query) {
Cursor cursor = null;
carrinhoDatabase.open();
try {
cursor = carrinhoDatabase.get().rawQuery(query, null);
} catch (Exception e) {
Log.d("CarrinhoDAOImpl",
"Method: findall().\nErro ao recuperar dados do banco. Causa: "
+ e.getMessage());
}
ArrayList<Carrinho> listEntity = null;
Carrinho entity;
if (cursor != null && !cursor.isClosed()) {
listEntity = new ArrayList<Carrinho>();
while (cursor.moveToNext()) {
entity = new Carrinho();
entity.setId(cursor.getLong(cursor.getColumnIndex(CarrinhoDatabaseHelper.COLUMN_ID)));
entity.setProduto_id(cursor.getLong(cursor.getColumnIndex(CarrinhoDatabaseHelper.COLUMN_PRODUTO)));
listEntity.add(entity);
}
cursor.close();
}
carrinhoDatabase.close();
return listEntity;
}
/**
* Remover
*/
@Override
public boolean remover(Long id, Context context, CarrinhoDatabase carrinhoDatabase) {
try {
carrinhoDatabase.open();
// (TABELA, COLUNA, WHERE CLAUSE)
carrinhoDatabase.get().delete(tableDAO, CarrinhoDatabaseHelper.COLUMN_ID + "=?",
new String[]{String.valueOf(id)});
} catch (Exception e) {
Log.d("CarrinhoDAOImpl",
"Method: remover().\nErro ao remover dados do banco. Causa: "
+ e.getMessage());
carrinhoDatabase.close();
return false;
}
carrinhoDatabase.close();
return true;
}
/**
* Total Itens
*/
@Override
public Double getTotalItens(Context context, CarrinhoDatabase carrinhoDatabase) {
Cursor cursor = null;
carrinhoDatabase.open();
try {
cursor = carrinhoDatabase.get().rawQuery("select produto_id from " + CarrinhoDatabaseHelper.NOME_TABELA , null);
} catch (Exception e) {
Log.d("CarrinhoDAOImpl",
"Method: getTotalItens().\nErro ao recuperar dados do banco. Causa: "
+ e.getMessage());
}
Double total = 0d;
Carrinho entity;
Produto produtoCarrinho;
if (cursor != null && !cursor.isClosed()) {
while (cursor.moveToNext()) {
entity = new Carrinho();
entity.setProduto_id(cursor.getLong(cursor.getColumnIndex("produto_id")));
entity.setProduto(context);
produtoCarrinho = entity.getProduto();
total += produtoCarrinho.getValor();
}
cursor.close();
}
carrinhoDatabase.close();
return total;
}
} | UTF-8 | Java | 4,414 | java | CarrinhoDAOImpl.java | Java | [
{
"context": "trade.repositories.CarrinhoDAO;\n\n/**\n * Created by charles on 21/11/15.\n */\npublic class CarrinhoDAOImpl imp",
"end": 519,
"score": 0.9965693950653076,
"start": 512,
"tag": "USERNAME",
"value": "charles"
}
] | null | [] | package br.com.interaje.easytrade.repositories.impl;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;
import java.util.ArrayList;
import br.com.interaje.easytrade.database.CarrinhoDatabase;
import br.com.interaje.easytrade.database.CarrinhoDatabaseHelper;
import br.com.interaje.easytrade.model.Carrinho;
import br.com.interaje.easytrade.model.Produto;
import br.com.interaje.easytrade.repositories.CarrinhoDAO;
/**
* Created by charles on 21/11/15.
*/
public class CarrinhoDAOImpl implements CarrinhoDAO {
private String tableDAO = "carrinho";
/**
* Inserir
*/
@Override
public boolean salvar(Carrinho carrinho, CarrinhoDatabase carrinhoDatabase) {
ContentValues cv = new ContentValues();
carrinhoDatabase.open();
try {
if (carrinho != null) {
cv.put(CarrinhoDatabaseHelper.COLUMN_PRODUTO, carrinho.getProduto_id());
carrinhoDatabase.get().insert(tableDAO, null, cv);
}
} catch (Exception e) {
Log.d("CarrinhoDAOImpl",
"Method: salvar().\nErro ao inserir dados do banco. Causa: "
+ e.getCause());
carrinhoDatabase.close();
return false;
}
carrinhoDatabase.close();
return true;
}
/**
* Listar todos
*/
@Override
public ArrayList<Carrinho> find(Context context, CarrinhoDatabase carrinhoDatabase, String query) {
Cursor cursor = null;
carrinhoDatabase.open();
try {
cursor = carrinhoDatabase.get().rawQuery(query, null);
} catch (Exception e) {
Log.d("CarrinhoDAOImpl",
"Method: findall().\nErro ao recuperar dados do banco. Causa: "
+ e.getMessage());
}
ArrayList<Carrinho> listEntity = null;
Carrinho entity;
if (cursor != null && !cursor.isClosed()) {
listEntity = new ArrayList<Carrinho>();
while (cursor.moveToNext()) {
entity = new Carrinho();
entity.setId(cursor.getLong(cursor.getColumnIndex(CarrinhoDatabaseHelper.COLUMN_ID)));
entity.setProduto_id(cursor.getLong(cursor.getColumnIndex(CarrinhoDatabaseHelper.COLUMN_PRODUTO)));
listEntity.add(entity);
}
cursor.close();
}
carrinhoDatabase.close();
return listEntity;
}
/**
* Remover
*/
@Override
public boolean remover(Long id, Context context, CarrinhoDatabase carrinhoDatabase) {
try {
carrinhoDatabase.open();
// (TABELA, COLUNA, WHERE CLAUSE)
carrinhoDatabase.get().delete(tableDAO, CarrinhoDatabaseHelper.COLUMN_ID + "=?",
new String[]{String.valueOf(id)});
} catch (Exception e) {
Log.d("CarrinhoDAOImpl",
"Method: remover().\nErro ao remover dados do banco. Causa: "
+ e.getMessage());
carrinhoDatabase.close();
return false;
}
carrinhoDatabase.close();
return true;
}
/**
* Total Itens
*/
@Override
public Double getTotalItens(Context context, CarrinhoDatabase carrinhoDatabase) {
Cursor cursor = null;
carrinhoDatabase.open();
try {
cursor = carrinhoDatabase.get().rawQuery("select produto_id from " + CarrinhoDatabaseHelper.NOME_TABELA , null);
} catch (Exception e) {
Log.d("CarrinhoDAOImpl",
"Method: getTotalItens().\nErro ao recuperar dados do banco. Causa: "
+ e.getMessage());
}
Double total = 0d;
Carrinho entity;
Produto produtoCarrinho;
if (cursor != null && !cursor.isClosed()) {
while (cursor.moveToNext()) {
entity = new Carrinho();
entity.setProduto_id(cursor.getLong(cursor.getColumnIndex("produto_id")));
entity.setProduto(context);
produtoCarrinho = entity.getProduto();
total += produtoCarrinho.getValor();
}
cursor.close();
}
carrinhoDatabase.close();
return total;
}
} | 4,414 | 0.575215 | 0.573629 | 152 | 28.019737 | 27.74614 | 124 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 9 |
4969072459f8c618121caaaf7e2a928fb64e9cca | 11,063,835,801,319 | 5f5ae1c82046b73636a8f9f64f8827721e15d752 | /Prog2/altKlausuren/KlausurSS15/Ware.java | b740a308e934ba34c5a11fbb33b57a55848c0708 | [] | no_license | SvenHerr/Prog2_Aufgaben_und_Altklausuren_mitEclipse_erstellt | https://github.com/SvenHerr/Prog2_Aufgaben_und_Altklausuren_mitEclipse_erstellt | 7a48ed6896bccee83f8c103e7f2ac72d313e1886 | abd49cbb0aa769c86fe8dc04410c1838a5acc959 | refs/heads/master | 2020-05-14T19:12:15.456000 | 2019-07-12T09:10:38 | 2019-07-12T09:10:38 | 181,925,100 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package KlausurSS15;
public class Ware extends UmsatzHelper implements IVerrechenbar
{
// muss nicht mit vererbung gemacht werden
private String bestellnr;
private double stuckzahl;
private double stueckpreis;
public Ware(String bestellnr, double stuckzahl, double stueckpreis)
{
this.bestellnr = bestellnr;
this.stuckzahl = stuckzahl;
this.stueckpreis = stueckpreis;
}
@Override
public double schreibeRechnung()
{
double ges_Betrag = this.stuckzahl * this.stueckpreis;
System.out.println("Best-Nr.: " + this.bestellnr + "\n"
+ "Stk.Anzahl: " + this.stuckzahl + "\n"
+ "Stk.Preis: " + this.stueckpreis + "\n"
+ "Gesamtbetrag: " + ges_Betrag +"\n");
return ges_Betrag;
}
}
| UTF-8 | Java | 720 | java | Ware.java | Java | [] | null | [] | package KlausurSS15;
public class Ware extends UmsatzHelper implements IVerrechenbar
{
// muss nicht mit vererbung gemacht werden
private String bestellnr;
private double stuckzahl;
private double stueckpreis;
public Ware(String bestellnr, double stuckzahl, double stueckpreis)
{
this.bestellnr = bestellnr;
this.stuckzahl = stuckzahl;
this.stueckpreis = stueckpreis;
}
@Override
public double schreibeRechnung()
{
double ges_Betrag = this.stuckzahl * this.stueckpreis;
System.out.println("Best-Nr.: " + this.bestellnr + "\n"
+ "Stk.Anzahl: " + this.stuckzahl + "\n"
+ "Stk.Preis: " + this.stueckpreis + "\n"
+ "Gesamtbetrag: " + ges_Betrag +"\n");
return ges_Betrag;
}
}
| 720 | 0.698611 | 0.695833 | 30 | 23 | 21.771542 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.633333 | false | false | 9 |
ec5337cfa7c9843f4e90932a6a599f080d120aa5 | 11,682,311,079,337 | 09d0ddd512472a10bab82c912b66cbb13113fcbf | /TestApplications/TF-BETA-THERMATK-v5.7.1/DecompiledCode/JADX/src/main/java/androidx/core/view/accessibility/AccessibilityEventCompat.java | 77dd1c440dc205a0ef8a268bae0c145dd1e38933 | [] | no_license | sgros/activity_flow_plugin | https://github.com/sgros/activity_flow_plugin | bde2de3745d95e8097c053795c9e990c829a88f4 | 9e59f8b3adacf078946990db9c58f4965a5ccb48 | refs/heads/master | 2020-06-19T02:39:13.865000 | 2019-07-08T20:17:28 | 2019-07-08T20:17:28 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package androidx.core.view.accessibility;
import android.os.Build.VERSION;
import android.view.accessibility.AccessibilityEvent;
public final class AccessibilityEventCompat {
public static void setContentChangeTypes(AccessibilityEvent accessibilityEvent, int i) {
if (VERSION.SDK_INT >= 19) {
accessibilityEvent.setContentChangeTypes(i);
}
}
public static int getContentChangeTypes(AccessibilityEvent accessibilityEvent) {
return VERSION.SDK_INT >= 19 ? accessibilityEvent.getContentChangeTypes() : 0;
}
}
| UTF-8 | Java | 561 | java | AccessibilityEventCompat.java | Java | [] | null | [] | package androidx.core.view.accessibility;
import android.os.Build.VERSION;
import android.view.accessibility.AccessibilityEvent;
public final class AccessibilityEventCompat {
public static void setContentChangeTypes(AccessibilityEvent accessibilityEvent, int i) {
if (VERSION.SDK_INT >= 19) {
accessibilityEvent.setContentChangeTypes(i);
}
}
public static int getContentChangeTypes(AccessibilityEvent accessibilityEvent) {
return VERSION.SDK_INT >= 19 ? accessibilityEvent.getContentChangeTypes() : 0;
}
}
| 561 | 0.745098 | 0.736185 | 16 | 34.0625 | 32.069199 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.375 | false | false | 9 |
bbb359c9a7b1fca8088700fcf84675212a595861 | 18,760,417,191,427 | deb423f6b82dbf1b405ad4b151e8def8f3d6e178 | /Rajasekhar/sample/src/Task_Methods/Method_7.java | 3e64e4f9b523213f1d3436c5d25bdc0774a6bcd9 | [] | no_license | Techiefrogs-Champs/Champs-01 | https://github.com/Techiefrogs-Champs/Champs-01 | 1dbc7b905fea1eb14d9b522b128f26d4d319db86 | 4873353c58a026425b38f97d9874de0eca0dc940 | refs/heads/master | 2023-02-28T13:16:48.730000 | 2021-02-08T05:09:36 | 2021-02-08T05:09:36 | 287,759,441 | 0 | 2 | null | false | 2020-11-24T05:50:16 | 2020-08-15T14:11:59 | 2020-11-24T05:50:17 | 2020-11-24T05:50:13 | 734 | 0 | 2 | 0 | Java | false | false | /* A class has an integer data member 'i' and a method named 'printNum' to print thevalue of 'i'.
Its subclass also has an integer data member 'j' and a method named 'printNum' to print the value of 'j'.
Make an object of the subclass and use it to assign a value to 'i' and to 'j'.
Now call the method 'printNum' by this object. */
package src.Task_Methods;
public class Method_7 extends A {
int j;
public void printNum(){
System.out.println(j);
}
public static void main(String[] args) {
Method_7 obj = new Method_7();
obj.i=888;
obj.j=999;
obj.printNum();
}
}
class A{
int i;
public void printNum(){
System.out.println(i);
}
} | UTF-8 | Java | 715 | java | Method_7.java | Java | [] | null | [] | /* A class has an integer data member 'i' and a method named 'printNum' to print thevalue of 'i'.
Its subclass also has an integer data member 'j' and a method named 'printNum' to print the value of 'j'.
Make an object of the subclass and use it to assign a value to 'i' and to 'j'.
Now call the method 'printNum' by this object. */
package src.Task_Methods;
public class Method_7 extends A {
int j;
public void printNum(){
System.out.println(j);
}
public static void main(String[] args) {
Method_7 obj = new Method_7();
obj.i=888;
obj.j=999;
obj.printNum();
}
}
class A{
int i;
public void printNum(){
System.out.println(i);
}
} | 715 | 0.625175 | 0.612587 | 25 | 27.639999 | 28.516493 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.36 | false | false | 9 |
b7d62dd120b9d852c8010182995abb2d8d4e778a | 10,307,921,527,589 | e4263b6346c2ad1cda131b9c7d53adc6f72c67e4 | /tcamt-web/src/main/java/gov/nist/healthcare/tcamt/web/UploadException.java | af5386560f0b4d4e0920456d7650a461c624302e | [] | no_license | usnistgov/tcamt | https://github.com/usnistgov/tcamt | df10682375a8b6dd255fcb126a9068fe4a44fd56 | 194e582b1bf3decd78f59c0c618aaabf87f04325 | refs/heads/master | 2020-05-21T04:48:44.575000 | 2019-02-20T18:43:38 | 2019-02-20T18:43:38 | 47,419,732 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* NIST IGAMT
* UploadException.java Apr 24, 2013
*
* This code was produced by the National Institute of Standards and
* Technology (NIST). See the "nist.disclaimer" file given in the distribution
* for information on the use and redistribution of this software.
*/
package gov.nist.healthcare.tcamt.web;
/**
* @author Harold Affo
*
*/
public class UploadException extends Exception {
private static final long serialVersionUID = 1134812461230576220L;
public UploadException(String error) {
super(error);
}
} | UTF-8 | Java | 554 | java | UploadException.java | Java | [
{
"context": " gov.nist.healthcare.tcamt.web;\r\n\r\n/**\r\n * @author Harold Affo\r\n * \r\n */\r\npublic class UploadException extends E",
"end": 354,
"score": 0.9998693466186523,
"start": 343,
"tag": "NAME",
"value": "Harold Affo"
}
] | null | [] | /*
* NIST IGAMT
* UploadException.java Apr 24, 2013
*
* This code was produced by the National Institute of Standards and
* Technology (NIST). See the "nist.disclaimer" file given in the distribution
* for information on the use and redistribution of this software.
*/
package gov.nist.healthcare.tcamt.web;
/**
* @author <NAME>
*
*/
public class UploadException extends Exception {
private static final long serialVersionUID = 1134812461230576220L;
public UploadException(String error) {
super(error);
}
} | 549 | 0.712996 | 0.66787 | 23 | 22.173914 | 26.161127 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.391304 | false | false | 9 |
09ee2ffaa4e54a4b5d0bd399377bde7e15c087d7 | 26,938,034,922,764 | ce22eb7af8e449bb9fe8ae55771f4e5932067a3f | /src/com/codefortomorrow/beginner/chapter3/examples/NonPrimitives.java | 05f5f561e9017a301122a11d66d86387d1256ece | [
"MIT"
] | permissive | code4tomorrow/java | https://github.com/code4tomorrow/java | 5e91dd91dbb760f47dc93663d3fc379ae6eb9556 | 0b3b77394bdea71781b2ac25b14eb271362c233b | refs/heads/master | 2023-06-01T05:15:27.320000 | 2021-07-07T18:11:22 | 2021-07-07T18:11:22 | 260,755,337 | 2 | 6 | MIT | false | 2021-07-07T18:11:23 | 2020-05-02T18:59:05 | 2021-07-07T12:07:09 | 2021-07-07T18:11:22 | 531 | 3 | 5 | 12 | Java | false | false | package com.codefortomorrow.beginner.chapter3.examples;
public class NonPrimitives {
public static void main(String[] args) {
// strings
String username = "JYOTI";
String password = "rani";
System.out.println("Username: " + username);
System.out.println("Password: " + password);
// string methods
System.out.println(username.toLowerCase());
System.out.println(password.toUpperCase());
System.out.println(username.substring(0, 4));
System.out.println(username.charAt(3));
// strings are immutable - even after method calls,
// username and password remain unchanged
System.out.println("Username: " + username);
System.out.println("Password: " + password);
// arrays preview
int[] numbers = { 4, 5, 1, -1, 10, 6 };
System.out.println("Element at index 2: " + numbers[2]);
}
}
| UTF-8 | Java | 925 | java | NonPrimitives.java | Java | [
{
"context": ") {\n // strings\n String username = \"JYOTI\";\n String password = \"rani\";\n\n Syst",
"end": 183,
"score": 0.9994747042655945,
"start": 178,
"tag": "USERNAME",
"value": "JYOTI"
},
{
"context": "ng username = \"JYOTI\";\n String password = \"rani\";\n\n System.out.println(\"Username: \" + user",
"end": 217,
"score": 0.9992349147796631,
"start": 213,
"tag": "PASSWORD",
"value": "rani"
}
] | null | [] | package com.codefortomorrow.beginner.chapter3.examples;
public class NonPrimitives {
public static void main(String[] args) {
// strings
String username = "JYOTI";
String password = "<PASSWORD>";
System.out.println("Username: " + username);
System.out.println("Password: " + password);
// string methods
System.out.println(username.toLowerCase());
System.out.println(password.toUpperCase());
System.out.println(username.substring(0, 4));
System.out.println(username.charAt(3));
// strings are immutable - even after method calls,
// username and password remain unchanged
System.out.println("Username: " + username);
System.out.println("Password: " + password);
// arrays preview
int[] numbers = { 4, 5, 1, -1, 10, 6 };
System.out.println("Element at index 2: " + numbers[2]);
}
}
| 931 | 0.611892 | 0.597838 | 28 | 32.035713 | 22.422058 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.714286 | false | false | 9 |
93937cf7eac7e3235f9de184e2401473715ec8b1 | 19,061,064,881,773 | 5d3cc1dc0fb8ced48154d1f8d6ef807dbc82ee8c | /CSE143Github/Sentimental Analysis/BookAnalyzer.java | dd599beacfdfc8145a48b2c8851125f87c7f116c | [
"MIT"
] | permissive | andrewmahoneyf/CSE-143 | https://github.com/andrewmahoneyf/CSE-143 | 0cdcbf5362da8781c41586316bae31216bb9281b | 9dd35b8ab7fdbc95032931bedaa45d5282feb573 | refs/heads/master | 2021-01-11T05:24:20.341000 | 2017-06-07T00:17:07 | 2017-06-07T00:17:07 | 69,786,771 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.io.*;
import java.util.*;
public class BookAnalyzer{
private Set<String> posWords;
private Set<String> negWords;
private ArrayList<String> bookWords;
private int negCount, posCount, mostNeg, mostPos; // variables for counting words
private long startTime, endTime, duration; // variables to keep track of time
// constructor takes in files for posWords, negWords, and a book
// constructs an array list for words in the book and turns pos/neg files to HashSets
// takes time of whole operation
public BookAnalyzer(File positive, File negative, File book) throws FileNotFoundException{
this.bookWords = new ArrayList<String>();
this.posWords = new HashSet<String>();
this.negWords = new HashSet<String>();
startTime = System.nanoTime();
Scanner bookScan = new Scanner(book);
while(bookScan.hasNext()) {
String word = bookScan.next().toLowerCase();
bookWords.add(word);
}
Scanner posScan = new Scanner(positive);
while(posScan.hasNext()) {
String word = posScan.next().toLowerCase();
posWords.add(word);
}
Scanner negScan = new Scanner(negative);
while(negScan.hasNext()) {
String word = negScan.next().toLowerCase();
negWords.add(word);
}
counter();
endTime = System.nanoTime();
duration = (endTime - startTime);
}
// returns the array size of bookWords for the total word count of the book
public int totalCount() {
return bookWords.size();
}
// goes through all the words in the book and counts if they are pos or neg
public void counter(){
for(int i = 0; i < bookWords.size(); i++){
if (negWords.contains(bookWords.get(i))){
negCount++;
}
if (posWords.contains(bookWords.get(i))){
posCount++;
}
}
}
// getter method for total negative word count
public int negCount() {
return negCount;
}
// getter method for total positive word count
public int posCount() {
return posCount;
}
// Decides genre of book based upon total count of neg and pos words
public String genre() {
if(posCount > negCount)
return "Comedy";
else if (posCount < negCount)
return "Tragedy";
else
return "Boring";
}
// gets the duration of the analysis
public long totalTime() {
return duration;
}
// finds positive word used the most and returns it with the amount of times
public String mostPos() {
int max = 0;
String commonWord = "no positive words found";
java.util.Iterator<String> iter = posWords.iterator();
while(iter.hasNext()) {
String temp = iter.next();
mostPos= Collections.frequency(bookWords, temp);
if(mostPos > max) {
commonWord = temp;
max = mostPos;
}
mostPos = max;
}
return commonWord + ", " + mostPos;
}
// finds negative word used the most and returns it with the amount of times
public String mostNeg() {
int max = 0;
String commonWord = "no negative words found";
java.util.Iterator<String> iter = negWords.iterator();
while(iter.hasNext()) {
String temp = iter.next();
mostNeg= Collections.frequency(bookWords, temp);
if(mostNeg > max) {
commonWord = temp;
max = mostNeg;
}
mostNeg = max;
}
return commonWord + ", " + mostNeg;
}
}
| UTF-8 | Java | 3,501 | java | BookAnalyzer.java | Java | [] | null | [] | import java.io.*;
import java.util.*;
public class BookAnalyzer{
private Set<String> posWords;
private Set<String> negWords;
private ArrayList<String> bookWords;
private int negCount, posCount, mostNeg, mostPos; // variables for counting words
private long startTime, endTime, duration; // variables to keep track of time
// constructor takes in files for posWords, negWords, and a book
// constructs an array list for words in the book and turns pos/neg files to HashSets
// takes time of whole operation
public BookAnalyzer(File positive, File negative, File book) throws FileNotFoundException{
this.bookWords = new ArrayList<String>();
this.posWords = new HashSet<String>();
this.negWords = new HashSet<String>();
startTime = System.nanoTime();
Scanner bookScan = new Scanner(book);
while(bookScan.hasNext()) {
String word = bookScan.next().toLowerCase();
bookWords.add(word);
}
Scanner posScan = new Scanner(positive);
while(posScan.hasNext()) {
String word = posScan.next().toLowerCase();
posWords.add(word);
}
Scanner negScan = new Scanner(negative);
while(negScan.hasNext()) {
String word = negScan.next().toLowerCase();
negWords.add(word);
}
counter();
endTime = System.nanoTime();
duration = (endTime - startTime);
}
// returns the array size of bookWords for the total word count of the book
public int totalCount() {
return bookWords.size();
}
// goes through all the words in the book and counts if they are pos or neg
public void counter(){
for(int i = 0; i < bookWords.size(); i++){
if (negWords.contains(bookWords.get(i))){
negCount++;
}
if (posWords.contains(bookWords.get(i))){
posCount++;
}
}
}
// getter method for total negative word count
public int negCount() {
return negCount;
}
// getter method for total positive word count
public int posCount() {
return posCount;
}
// Decides genre of book based upon total count of neg and pos words
public String genre() {
if(posCount > negCount)
return "Comedy";
else if (posCount < negCount)
return "Tragedy";
else
return "Boring";
}
// gets the duration of the analysis
public long totalTime() {
return duration;
}
// finds positive word used the most and returns it with the amount of times
public String mostPos() {
int max = 0;
String commonWord = "no positive words found";
java.util.Iterator<String> iter = posWords.iterator();
while(iter.hasNext()) {
String temp = iter.next();
mostPos= Collections.frequency(bookWords, temp);
if(mostPos > max) {
commonWord = temp;
max = mostPos;
}
mostPos = max;
}
return commonWord + ", " + mostPos;
}
// finds negative word used the most and returns it with the amount of times
public String mostNeg() {
int max = 0;
String commonWord = "no negative words found";
java.util.Iterator<String> iter = negWords.iterator();
while(iter.hasNext()) {
String temp = iter.next();
mostNeg= Collections.frequency(bookWords, temp);
if(mostNeg > max) {
commonWord = temp;
max = mostNeg;
}
mostNeg = max;
}
return commonWord + ", " + mostNeg;
}
}
| 3,501 | 0.617823 | 0.616967 | 115 | 29.434782 | 22.247669 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.947826 | false | false | 9 |
73fbdbfdc5abe69a6291916f76390835ead3f49d | 19,061,064,881,167 | 37bf97e47519593771bbb38e41d6aa42c6021e1c | /src/main/java/com/chow/dao/mongo/impl/DataHandleDaoImpl.java | c11de3f317b59e0795e11bcb86de180dfb299af1 | [] | no_license | chowsanity2/shanghaiTest | https://github.com/chowsanity2/shanghaiTest | f69978e1b039ef4dd0165f1e831f10f9b8d464a4 | c24c8e23c8ed2fd39a620a085e3f25bfb39d5483 | refs/heads/master | 2020-03-19T07:30:46.494000 | 2019-01-15T09:53:07 | 2019-01-15T09:53:07 | 136,120,467 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.chow.dao.mongo.impl;
import com.alibaba.fastjson.JSONArray;
import com.chow.dao.*;
import com.chow.dao.mongo.DataHandleDao;
import com.chow.model.*;
import com.chow.model.mongoPo.MShopSaleDataSeq;
import com.chow.model.mongoPo.MShopSaleDetail;
import com.chow.model.mongoPo.McheckTicket;
import com.chow.model.mongoPo.MticketSaleDetail;
import com.chow.model.vo.Con4Budget;
import com.chow.utils.ConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import java.math.BigDecimal;
import java.util.*;
/**
* 拉取数据
* "0:失败 1:成功"
*/
public class DataHandleDaoImpl extends AbstractBaseMongoTemplete implements DataHandleDao {
@Autowired
private BatchMapper batchMapper;
@Autowired
private LayoutMapper layoutMapper;
@Autowired
private TicketSaleMapper ticketSaleMapper;
@Autowired
private BudgetMapper budgetMapper;
@Autowired
private ShopSaleMapper shopSaleMapper;
@Autowired
private IncomeReportMapper incomeReportMapper;
@Autowired
private TicketReportMapper ticketReportMapper;
@Autowired
private CheckTicketMapper checkTicketMapper;
@Override
public int saveAllSale() throws Exception{
//准备存储售票和商品销售信息存放的容器,每条不重复数据会分为3*4份注入到报表
//根据Project_Level划分
Map<String,Map<String,IncomeReport>> layoutSaleMap = new HashMap<>();
Map<String,Map<String,IncomeReport>> projectSaleMap = new HashMap<>();
Map<String,Map<String,IncomeReport>> buildingSaleMap = new HashMap<>();
//根据日期划分
Map<String,IncomeReport> projectSaleMap4Date = new HashMap<>();
Map<String,IncomeReport> layoutSaleMap4Date = new HashMap<>();
Map<String,IncomeReport> buildingSaleMap4Date = new HashMap<>();
//获取批次表layout为3信息
List<String> batchNumbers = batchMapper.findBatchByLayoutId(3);
Query query = new Query();
Criteria criteria = Criteria.where("seqId").in(batchNumbers);
query.addCriteria(criteria);
List<MticketSaleDetail> mtList = mongoTemplate.find(query, MticketSaleDetail.class);
for (MticketSaleDetail mticketSaleDetail:mtList) {
String data = mticketSaleDetail.getData();
//json转集合
List<Map<String,Object>> dataList = (List<Map<String,Object>>)JSONArray.parse(data);
for (Map<String,Object> map:dataList) {
TicketSale ticketSale = new TicketSale();
ticketSale.setProjectId((String)map.get("PROJECT_ID"));
ticketSale.setProjectName((String)map.get("PROJECT_NAME"));
ticketSale.setDealId(String.valueOf((int)map.get("DEAL_ID")));
// ticketSale.setDealType((String)map.get("DEAL_TYPE"));
ticketSale.setAgencyName((String) map.get("AGENCY_NAME"));
ticketSale.setTerminalName((String)map.get("TERMINAL_NAME"));
ticketSale.setSaleDate(((String)map.get("SALE_DATE")));
ticketSale.setLayoutId(Integer.valueOf(mticketSaleDetail.getLayoutId()));
Layout layout = layoutMapper.selectByPrimaryKey(Integer.valueOf(mticketSaleDetail.getLayoutId()));
ticketSale.setLayoutName(layout.getLayoutName());
ticketSale.setTicketPrice((BigDecimal) map.get("TICKET_PRICE"));
ticketSale.setTicketCount((int)map.get("TICKET_COUNT"));
ticketSale.setTicketAmount(((BigDecimal)map.get("TICKET_AMOUNT")));
ticketSale.setDiscount((String)map.get("DISCOUNT"));
ticketSale.setTicketPeople((int)map.get("TICKET_PEOPLE"));
ticketSale.setEmpName((String)map.get("EMP_NAME"));
ticketSale.setCollectTerminalName((String)map.get("COLLECT_TERMINAL_NAME"));
ticketSale.setBarcode((String)map.get("BARCODE"));
ticketSale.setEmpName((String)map.get("EMP_NAME"));
ticketSale.setTicketCode((String)map.get("TICKET_CODE"));
ticketSale.setGzone((String)map.get("GZONE"));
ticketSale.setTicketType((String)map.get("TICKET_TYPE"));
ticketSaleMapper.insert(ticketSale);
//分析数据存入报表
//将日期分类转换为固定格式
String dateStr = ticketSale.getSaleDate();
Date date = ConvertUtils.convertStr2Date(dateStr);
String yearFormat = ConvertUtils.convertDate2Year(date);
String quarterFormat = ConvertUtils.convertDate2Quarter(date);
String monthFormat = ConvertUtils.convertDate2Month(date);
String dayFormat = ConvertUtils.convertDate2Day(date);
//准备IncomeReport
IncomeReport income4year = new IncomeReport();
IncomeReport income4quarter = new IncomeReport();
IncomeReport income4month = new IncomeReport();
IncomeReport income4day = new IncomeReport();
IncomeReport income4Layoutyear = new IncomeReport();
IncomeReport income4Layoutquarter = new IncomeReport();
IncomeReport income4Layoutmonth = new IncomeReport();
IncomeReport income4Layoutday = new IncomeReport();
//暂时没数据
IncomeReport income4Buildyear = new IncomeReport();
IncomeReport income4Buildquarter = new IncomeReport();
IncomeReport income4Buildmonth = new IncomeReport();
IncomeReport income4Buildday = new IncomeReport();
//根据项目分类 Project_Level为2
//判断Map中是否存在该项目
if(projectSaleMap.containsKey(ticketSale.getProjectId())){
/*
存在,判断日期是否存在,需要累加的两个参数
1.该业态销售总额TypeAmount
2.售票数量BookingCount
*/
if(projectSaleMap4Date.containsKey(ticketSale.getProjectId()+","+yearFormat)){
//System.out.println("==============项目年份存在数据累加");
comp(projectSaleMap4Date,ticketSale,yearFormat,2,mticketSaleDetail);
}else{
//年份不存在,添加
//System.out.println("==============项目年份不存在添加");
comp2(projectSaleMap4Date,ticketSale,income4year,yearFormat,2,4,mticketSaleDetail);
}
if(projectSaleMap4Date.containsKey(ticketSale.getProjectId()+","+quarterFormat)){
//System.out.println("==============项目季度存在数据累加");
//季度存在,累加数据
comp(projectSaleMap4Date,ticketSale,quarterFormat,2,mticketSaleDetail);
}else{
//季度不存在,添加
//System.out.println("==============季度不存在添加");
comp2(projectSaleMap4Date,ticketSale,income4quarter,quarterFormat,2,3,mticketSaleDetail);
}
if(projectSaleMap4Date.containsKey(ticketSale.getProjectId()+","+monthFormat)){
//System.out.println("==============项目月份存在数据累加");
//月份存在,累加数据
comp(projectSaleMap4Date,ticketSale,monthFormat,2,mticketSaleDetail);
}else{
//System.out.println("==============月份不存在添加");
//月份不存在,添加
comp2(projectSaleMap4Date,ticketSale,income4month,monthFormat,2,2,mticketSaleDetail);
}
if(projectSaleMap4Date.containsKey(ticketSale.getProjectId()+","+dayFormat)){
//System.out.println("==============项目天存在数据累加");
//天存在,累加数据
comp(projectSaleMap4Date,ticketSale,dayFormat,2,mticketSaleDetail);
}else{
//System.out.println("==============天不存在添加");
//天不存在,添加
comp2(projectSaleMap4Date,ticketSale,income4day,dayFormat,2,1,mticketSaleDetail);
}
}else{
//System.out.println("==============1初始化数据");
//项目不存在,初始化数据
comp2(projectSaleMap4Date,ticketSale,income4year,yearFormat,2,4,mticketSaleDetail);
comp2(projectSaleMap4Date,ticketSale,income4quarter,quarterFormat,2,3,mticketSaleDetail);
comp2(projectSaleMap4Date,ticketSale,income4month,monthFormat,2,2,mticketSaleDetail);
comp2(projectSaleMap4Date,ticketSale,income4day,dayFormat,2,1,mticketSaleDetail);
//装载
projectSaleMap4Date.put(ticketSale.getProjectId()+","+yearFormat,income4year);
projectSaleMap4Date.put(ticketSale.getProjectId()+","+quarterFormat,income4quarter);
projectSaleMap4Date.put(ticketSale.getProjectId()+","+monthFormat,income4month);
projectSaleMap4Date.put(ticketSale.getProjectId()+","+dayFormat,income4day);
}
projectSaleMap.put(ticketSale.getProjectId(),null);
//根据项目分类 Project_Level为1
//判断Map中是否存在该商铺
if(buildingSaleMap.containsKey(mticketSaleDetail.getBuildingCode())){
/*
存在,判断日期是否存在,需要累加的两个参数
1.该商铺销售总额TypeAmount
2.售票数量BookingCount
*/
if(buildingSaleMap4Date.containsKey(mticketSaleDetail.getBuildingCode()+","+yearFormat)){
//System.out.println("==============商铺年份存在数据累加");
comp(buildingSaleMap4Date,ticketSale,yearFormat,1,mticketSaleDetail);
}else{
//年份不存在,添加
//System.out.println("==============年份不存在添加");
comp2(buildingSaleMap4Date,ticketSale,income4Buildyear,yearFormat,1,4,mticketSaleDetail);
}
if(buildingSaleMap4Date.containsKey(mticketSaleDetail.getBuildingCode()+","+quarterFormat)){
//System.out.println("==============商铺季度存在数据累加");
//季度存在,累加数据
comp(buildingSaleMap4Date,ticketSale,quarterFormat,1,mticketSaleDetail);
}else{
//季度不存在,添加
//System.out.println("==============季度不存在添加");
comp2(buildingSaleMap4Date,ticketSale,income4Buildquarter,quarterFormat,1,3,mticketSaleDetail);
}
if(buildingSaleMap4Date.containsKey(mticketSaleDetail.getBuildingCode()+","+monthFormat)){
//System.out.println("==============商铺月份存在数据累加");
//月份存在,累加数据
comp(buildingSaleMap4Date,ticketSale,monthFormat,1,mticketSaleDetail);
}else{
//System.out.println("==============月份不存在添加");
//月份不存在,添加
comp2(buildingSaleMap4Date,ticketSale,income4Buildmonth,monthFormat,1,2,mticketSaleDetail);
}
if(buildingSaleMap4Date.containsKey(mticketSaleDetail.getBuildingCode()+","+dayFormat)){
//System.out.println("==============商铺天存在数据累加");
//天存在,累加数据
comp(buildingSaleMap4Date,ticketSale,dayFormat,1,mticketSaleDetail);
}else{
//System.out.println("==============天不存在添加");
//天不存在,添加
comp2(buildingSaleMap4Date,ticketSale,income4Buildday,dayFormat,1,1,mticketSaleDetail);
}
}else{
//System.out.println("==============2初始化数据");
//项目不存在,初始化数据
comp2(buildingSaleMap4Date,ticketSale,income4Buildyear,yearFormat,1,4,mticketSaleDetail);
comp2(buildingSaleMap4Date,ticketSale,income4Buildquarter,quarterFormat,1,3,mticketSaleDetail);
comp2(buildingSaleMap4Date,ticketSale,income4Buildmonth,monthFormat,1,2,mticketSaleDetail);
comp2(buildingSaleMap4Date,ticketSale,income4Buildday,dayFormat,1,1,mticketSaleDetail);
//装载
buildingSaleMap4Date.put(mticketSaleDetail.getBuildingCode()+","+yearFormat,income4Buildyear);
buildingSaleMap4Date.put(mticketSaleDetail.getBuildingCode()+","+quarterFormat,income4Buildquarter);
buildingSaleMap4Date.put(mticketSaleDetail.getBuildingCode()+","+monthFormat,income4Buildmonth);
buildingSaleMap4Date.put(mticketSaleDetail.getBuildingCode()+","+dayFormat,income4Buildday);
}
buildingSaleMap.put(mticketSaleDetail.getBuildingCode(),null);
//根据业态分类 Project_Level为0
//判断Map中是否存在该业态
if(layoutSaleMap.containsKey(ticketSale.getLayoutId().toString())){
/*
存在,判断日期是否存在,需要累加的两个参数
1.该业态销售总额TypeAmount
2.售票数量BookingCount
*/
if(layoutSaleMap4Date.containsKey(ticketSale.getLayoutId().toString()+","+yearFormat)){
//System.out.println("==============业态年份存在数据累加");
comp(layoutSaleMap4Date,ticketSale,yearFormat,0,mticketSaleDetail);
}else{
//年份不存在,添加
//System.out.println("==============年份不存在添加");
comp2(layoutSaleMap4Date,ticketSale,income4Layoutyear,yearFormat,0,4,mticketSaleDetail);
}
if(layoutSaleMap4Date.containsKey(ticketSale.getLayoutId().toString()+","+quarterFormat)){
//System.out.println("==============业态季度存在数据累加");
//季度存在,累加数据
comp(layoutSaleMap4Date,ticketSale,quarterFormat,0,mticketSaleDetail);
}else{
//季度不存在,添加
//System.out.println("==============季度不存在添加");
comp2(layoutSaleMap4Date,ticketSale,income4Layoutquarter,quarterFormat,0,3,mticketSaleDetail);
}
if(layoutSaleMap4Date.containsKey(ticketSale.getLayoutId().toString()+","+monthFormat)){
//System.out.println("==============业态月份存在数据累加");
//月份存在,累加数据
comp(layoutSaleMap4Date,ticketSale,monthFormat,0,mticketSaleDetail);
}else{
//System.out.println("==============月份不存在添加");
//月份不存在,添加
comp2(layoutSaleMap4Date,ticketSale,income4Layoutmonth,monthFormat,0,2,mticketSaleDetail);
}
if(layoutSaleMap4Date.containsKey(ticketSale.getLayoutId().toString()+","+dayFormat)){
//System.out.println("==============业态天存在数据累加");
//天存在,累加数据
comp(layoutSaleMap4Date,ticketSale,dayFormat,0,mticketSaleDetail);
}else{
//System.out.println("==============天不存在添加");
//天不存在,添加
comp2(layoutSaleMap4Date,ticketSale,income4Layoutday,dayFormat,0,1,mticketSaleDetail);
}
}else{
//业态不存在,初始化数据
comp2(layoutSaleMap4Date,ticketSale,income4Layoutyear,yearFormat,0,4,mticketSaleDetail);
comp2(layoutSaleMap4Date,ticketSale,income4Layoutquarter,quarterFormat,0,3,mticketSaleDetail);
comp2(layoutSaleMap4Date,ticketSale,income4Layoutmonth,monthFormat,0,2,mticketSaleDetail);
comp2(layoutSaleMap4Date,ticketSale,income4Layoutday,dayFormat,0,1,mticketSaleDetail);
//装载
layoutSaleMap4Date.put(ticketSale.getLayoutId().toString()+","+yearFormat,income4Layoutyear);
layoutSaleMap4Date.put(ticketSale.getLayoutId().toString()+","+quarterFormat,income4Layoutquarter);
layoutSaleMap4Date.put(ticketSale.getLayoutId().toString()+","+monthFormat,income4Layoutmonth);
layoutSaleMap4Date.put(ticketSale.getLayoutId().toString()+","+dayFormat,income4Layoutday);
}
layoutSaleMap.put(ticketSale.getLayoutId().toString(),null);
}
}
//获取批次表layout不为3和6,10的信息
batchNumbers = batchMapper.findBatchNotLayoutId(3);
query = new Query();
Criteria criteria1 = Criteria.where("seqId").in(batchNumbers);
query.addCriteria(criteria1);
List<MShopSaleDetail> mticketSaleDetailList = mongoTemplate.find(query, MShopSaleDetail.class);
for (MShopSaleDetail mShopSaleDetail:mticketSaleDetailList) {
String dataList = mShopSaleDetail.getData();
List<Map<String,Object>> data = (List<Map<String,Object>>)JSONArray.parse(dataList);
for (Map<String,Object> map:data) {
ShopSale sale = new ShopSale();
sale.setProjectId((String) map.get("PROJECT_ID"));
sale.setProjectName((String)map.get("PROJECT_NAME"));
sale.setSaleType((String)map.get("SALE_TYPE"));
sale.setShopId((int)map.get("SHOP_ID"));
sale.setSalePrice((BigDecimal)map.get("SALE_PRICE"));
sale.setSaleCount(String.valueOf((BigDecimal)map.get("SALE_COUNT")));
sale.setSaleDate(ConvertUtils.convertDate((String)map.get("SALE_DATE")));
sale.setShopPrice((BigDecimal) map.get("SHOP_PRICE"));
sale.setLayoutId(Integer.parseInt(mShopSaleDetail.getLayoutId()));
Layout layout = layoutMapper.selectByPrimaryKey(Integer.valueOf(mShopSaleDetail.getLayoutId()));
sale.setLayoutName(layout.getLayoutName());
shopSaleMapper.insert(sale);
//分析数据存入报表
//将日期分类转换为固定格式
Date date = sale.getSaleDate();
String yearFormat = ConvertUtils.convertDate2Year(date);
String quarterFormat = ConvertUtils.convertDate2Quarter(date);
String monthFormat = ConvertUtils.convertDate2Month(date);
String dayFormat = ConvertUtils.convertDate2Day(date);
//准备IncomeReport
IncomeReport income4year = new IncomeReport();
IncomeReport income4quarter = new IncomeReport();
IncomeReport income4month = new IncomeReport();
IncomeReport income4day = new IncomeReport();
IncomeReport income4Layoutyear = new IncomeReport();
IncomeReport income4Layoutquarter = new IncomeReport();
IncomeReport income4Layoutmonth = new IncomeReport();
IncomeReport income4Layoutday = new IncomeReport();
IncomeReport income4Buildyear = new IncomeReport();
IncomeReport income4Buildquarter = new IncomeReport();
IncomeReport income4Buildmonth = new IncomeReport();
IncomeReport income4Buildday = new IncomeReport();
//根据业态分类 Project_Level为0
//判断Map中是否存在该业态
if(layoutSaleMap.containsKey(sale.getLayoutId().toString())){
/*
存在,判断日期是否存在,需要累加的一个参数
1.该业态销售总额TypeAmount
*/
if(layoutSaleMap4Date.containsKey(sale.getLayoutId().toString()+","+yearFormat)){
//System.out.println("==============业态年份存在数据累加");
comp3(layoutSaleMap4Date,sale,yearFormat,0,mShopSaleDetail);
}else{
//年份不存在,添加
//System.out.println("==============年份不存在添加");
comp4(layoutSaleMap4Date,sale,income4Layoutyear,yearFormat,0,4,mShopSaleDetail);
}
if(projectSaleMap4Date.containsKey(sale.getLayoutId().toString()+","+quarterFormat)){
//System.out.println("==============业态季度存在数据累加");
//季度存在,累加数据
comp3(layoutSaleMap4Date,sale,quarterFormat,0,mShopSaleDetail);
}else{
//季度不存在,添加
//System.out.println("==============季度不存在添加");
comp4(layoutSaleMap4Date,sale,income4Layoutquarter,quarterFormat,0,3,mShopSaleDetail);
}
if(layoutSaleMap4Date.containsKey(sale.getLayoutId().toString()+","+monthFormat)){
//System.out.println("==============业态月份存在数据累加");
//月份存在,累加数据
comp3(layoutSaleMap4Date,sale,monthFormat,0,mShopSaleDetail);
}else{
//System.out.println("==============月份不存在添加");
//月份不存在,添加
comp4(layoutSaleMap4Date,sale,income4Layoutmonth,monthFormat,0,2,mShopSaleDetail);
}
if(layoutSaleMap4Date.containsKey(sale.getLayoutId().toString()+","+dayFormat)){
//System.out.println("==============业态天存在数据累加");
//天存在,累加数据
comp3(layoutSaleMap4Date,sale,dayFormat,0,mShopSaleDetail);
}else{
//System.out.println("==============天不存在添加");
//天不存在,添加
comp4(layoutSaleMap4Date,sale,income4Layoutday,dayFormat,0,1,mShopSaleDetail);
}
}else{
//System.out.println("==============2初始化数据");
//业态不存在,初始化数据
comp4(layoutSaleMap4Date,sale,income4Layoutyear,yearFormat,0,4,mShopSaleDetail);
comp4(layoutSaleMap4Date,sale,income4Layoutquarter,quarterFormat,0,3,mShopSaleDetail);
comp4(layoutSaleMap4Date,sale,income4Layoutmonth,monthFormat,0,2,mShopSaleDetail);
comp4(layoutSaleMap4Date,sale,income4Layoutday,dayFormat,0,1,mShopSaleDetail);
//装载
layoutSaleMap4Date.put(sale.getLayoutId().toString()+","+yearFormat,income4Layoutyear);
layoutSaleMap4Date.put(sale.getLayoutId().toString()+","+quarterFormat,income4Layoutquarter);
layoutSaleMap4Date.put(sale.getLayoutId().toString()+","+monthFormat,income4Layoutmonth);
layoutSaleMap4Date.put(sale.getLayoutId().toString()+","+dayFormat,income4Layoutday);
}
layoutSaleMap.put(sale.getLayoutId().toString(),null);
//根据商铺分类 Project_Level为1
//判断Map中是否存在该商铺
if(layoutSaleMap.containsKey(mShopSaleDetail.getBuildingCode())){
/*
存在,判断日期是否存在,需要累加的一个参数
1.该商铺销售总额TypeAmount
*/
if(buildingSaleMap4Date.containsKey(mShopSaleDetail.getBuildingCode()+","+yearFormat)){
//System.out.println("==============商铺年份存在数据累加");
comp3(buildingSaleMap4Date,sale,yearFormat,1,mShopSaleDetail);
}else{
//年份不存在,添加
//System.out.println("==============年份不存在添加");
comp4(buildingSaleMap4Date,sale,income4Buildyear,yearFormat,1,4,mShopSaleDetail);
}
if(buildingSaleMap4Date.containsKey(mShopSaleDetail.getBuildingCode()+","+quarterFormat)){
//System.out.println("==============商铺季度存在数据累加");
//季度存在,累加数据
comp3(buildingSaleMap4Date,sale,quarterFormat,1,mShopSaleDetail);
}else{
//季度不存在,添加
//System.out.println("==============季度不存在添加");
comp4(buildingSaleMap4Date,sale,income4Buildquarter,quarterFormat,1,3,mShopSaleDetail);
}
if(buildingSaleMap4Date.containsKey(mShopSaleDetail.getBuildingCode()+","+monthFormat)){
//System.out.println("==============商铺月份存在数据累加");
//月份存在,累加数据
comp3(buildingSaleMap4Date,sale,monthFormat,1,mShopSaleDetail);
}else{
//System.out.println("==============月份不存在添加");
//月份不存在,添加
comp4(buildingSaleMap4Date,sale,income4Buildmonth,monthFormat,1,2,mShopSaleDetail);
}
if(buildingSaleMap4Date.containsKey(mShopSaleDetail.getBuildingCode()+","+dayFormat)){
//System.out.println("==============商铺天存在数据累加");
//天存在,累加数据
comp3(buildingSaleMap4Date,sale,dayFormat,1,mShopSaleDetail);
}else{
//System.out.println("==============天不存在添加");
//天不存在,添加
comp4(buildingSaleMap4Date,sale,income4Buildday,dayFormat,1,1,mShopSaleDetail);
}
}else{
//System.out.println("==============3初始化数据");
//业态不存在,初始化数据
comp4(buildingSaleMap4Date,sale,income4Buildyear,yearFormat,1,4,mShopSaleDetail);
comp4(buildingSaleMap4Date,sale,income4Buildquarter,quarterFormat,1,3,mShopSaleDetail);
comp4(buildingSaleMap4Date,sale,income4Buildmonth,monthFormat,1,2,mShopSaleDetail);
comp4(buildingSaleMap4Date,sale,income4Buildday,dayFormat,1,1,mShopSaleDetail);
//装载
buildingSaleMap4Date.put(mShopSaleDetail.getBuildingCode()+","+yearFormat,income4Buildyear);
buildingSaleMap4Date.put(mShopSaleDetail.getBuildingCode()+","+quarterFormat,income4Buildquarter);
buildingSaleMap4Date.put(mShopSaleDetail.getBuildingCode()+","+monthFormat,income4Buildmonth);
buildingSaleMap4Date.put(mShopSaleDetail.getBuildingCode()+","+dayFormat,income4Buildday);
}
buildingSaleMap.put(mShopSaleDetail.getBuildingCode(),null);
//根据项目分类 Project_Level为2
//判断Map中是否存在该项目
if(projectSaleMap.containsKey(sale.getProjectId())){
/*
存在,判断日期是否存在,需要累加的一个参数
1.该业态销售总额TypeAmount
*/
if(projectSaleMap4Date.containsKey(sale.getProjectId()+","+yearFormat)){
//System.out.println("==============项目年份存在数据累加");
comp3(projectSaleMap4Date,sale,yearFormat,2,mShopSaleDetail);
}else{
//年份不存在,添加
//System.out.println("==============项目年份不存在添加");
comp4(projectSaleMap4Date,sale,income4year,yearFormat,2,4,mShopSaleDetail);
}
if(projectSaleMap4Date.containsKey(sale.getProjectId()+","+quarterFormat)){
//System.out.println("==============项目季度存在数据累加");
//季度存在,累加数据
comp3(projectSaleMap4Date,sale,quarterFormat,2,mShopSaleDetail);
}else{
//季度不存在,添加
//System.out.println("==============季度不存在添加");
comp4(projectSaleMap4Date,sale,income4quarter,quarterFormat,2,3,mShopSaleDetail);
}
if(projectSaleMap4Date.containsKey(sale.getProjectId()+","+monthFormat)){
//System.out.println("==============项目月份存在数据累加");
//月份存在,累加数据
comp3(projectSaleMap4Date,sale,monthFormat,2,mShopSaleDetail);
}else{
//System.out.println("==============月份不存在添加");
//月份不存在,添加
comp4(projectSaleMap4Date,sale,income4month,monthFormat,2,2,mShopSaleDetail);
}
if(projectSaleMap4Date.containsKey(sale.getProjectId()+","+dayFormat)){
//System.out.println("==============项目天存在数据累加");
//天存在,累加数据
comp3(projectSaleMap4Date,sale,dayFormat,2,mShopSaleDetail);
}else{
//System.out.println("==============天不存在添加");
//天不存在,添加
comp4(projectSaleMap4Date,sale,income4day,dayFormat,2,1,mShopSaleDetail);
}
}else{
//System.out.println("==============1初始化数据");
//业态不存在,初始化数据
comp4(projectSaleMap4Date,sale,income4year,yearFormat,2,4,mShopSaleDetail);
comp4(projectSaleMap4Date,sale,income4quarter,quarterFormat,2,3,mShopSaleDetail);
comp4(projectSaleMap4Date,sale,income4month,monthFormat,2,2,mShopSaleDetail);
comp4(projectSaleMap4Date,sale,income4day,dayFormat,2,1,mShopSaleDetail);
//装载
projectSaleMap4Date.put(sale.getProjectId()+","+yearFormat,income4year);
projectSaleMap4Date.put(sale.getProjectId()+","+quarterFormat,income4quarter);
projectSaleMap4Date.put(sale.getProjectId()+","+monthFormat,income4month);
projectSaleMap4Date.put(sale.getProjectId()+","+dayFormat,income4day);
}
projectSaleMap.put(sale.getProjectId(),null);
}
}
//计算salePercent
//project
salePercentCalc(projectSaleMap4Date);
//layout
salePercentCalc(layoutSaleMap4Date);
//building
salePercentCalc(buildingSaleMap4Date);
//装载saleMap
//project
filterMap(projectSaleMap,projectSaleMap4Date);
//layout
filterMap(layoutSaleMap,layoutSaleMap4Date);
//building
filterMap(buildingSaleMap,buildingSaleMap4Date);
//注入到mysql
for (Map.Entry<String,Map<String,IncomeReport>> layout:layoutSaleMap.entrySet()) {
for (Map.Entry<String,IncomeReport> layout4Date:layout.getValue().entrySet()) {
IncomeReport income = layout4Date.getValue();
incomeReportMapper.insert(income);
}
}
for (Map.Entry<String,Map<String,IncomeReport>> project:projectSaleMap.entrySet()) {
for (Map.Entry<String,IncomeReport> project4Date:project.getValue().entrySet()) {
IncomeReport income = project4Date.getValue();
incomeReportMapper.insert(income);
}
}
for (Map.Entry<String,Map<String,IncomeReport>> build:buildingSaleMap.entrySet()) {
for (Map.Entry<String,IncomeReport> build4Date:build.getValue().entrySet()) {
IncomeReport income = build4Date.getValue();
incomeReportMapper.insert(income);
}
}
return 0;
}
@Override
public int saveCheckTicket() throws Exception{
//准备检票信息存放的容器,每条不重复数据会分为3*4份注入到报表
//根据Project_Level划分
Map<String,Map<String,TicketReport>> layoutCheckMap = new HashMap<>();
Map<String,Map<String,TicketReport>> projectCheckMap = new HashMap<>();
Map<String,Map<String,TicketReport>> buildingCheckMap = new HashMap<>();
//根据日期划分
Map<String,TicketReport> projectCheckMap4Date = new HashMap<>();
Map<String,TicketReport> layoutCheckMap4Date = new HashMap<>();
Map<String,TicketReport> buildingCheckMap4Date = new HashMap<>();
//获取批次表layout为6信息,检票
List<String> batchNumbers = batchMapper.findBatchByLayoutId(6);
Query query = new Query();
Criteria criteria = Criteria.where("seqId").in(batchNumbers);
query.addCriteria(criteria);
List<McheckTicket> mtList = mongoTemplate.find(query, McheckTicket.class);
for (McheckTicket mcheckTicket:mtList) {
String data = mcheckTicket.getData();
if(data==null){
continue;
}
List<Map<String,Object>> dataList = (List<Map<String, Object>>)JSONArray.parse(data);
for (Map<String,Object> map:dataList) {
CheckTicket checkTicket = new CheckTicket();
checkTicket.setProjectId((String) map.get("PROJECT_ID"));
checkTicket.setProjectName((String) map.get("PROJECT_NAME"));
checkTicket.setBatchNumber(mcheckTicket.getSeqId());
checkTicket.setDealId(String.valueOf((int) map.get("DEAL_ID")));
checkTicket.setTicketType((String) map.get("TICKET_TYPE"));
checkTicket.setBarcode((String) map.get("BARCODE"));
//checkTicket.setTicketName((String) map.get("PROJECT_ID"));
checkTicket.setGzone((String) map.get("GZONE"));
checkTicket.setInGardenDate(ConvertUtils.convertDate((String)map.get("IN_GARDEN_DATE")));
checkTicket.setDeviceName((String) map.get("DEVICE_NAME"));
checkTicket.setIncount((Integer) map.get("INCOUNT"));
checkTicket.setCheckCount((Integer) map.get("INCOUNT"));
checkTicket.setType((String) map.get("TYPE"));
checkTicket.setTicketType((String) map.get("TICKET_TYPE"));
checkTicket.setTicketCode((String) map.get("TICKET_CODE"));
checkTicket.setCheckDate(ConvertUtils.convertDate((String) map.get("CHECK_DATE")));
checkTicket.setTicketPrice( (BigDecimal)map.get("TICKET_PRICE"));
checkTicket.setDiscount(String.valueOf(map.get("DISCOUNT")) );
checkTicket.setTicketAmount( (BigDecimal)map.get("TICKET_AMOUNT"));
checkTicket.setTicketPeople((int)map.get("TICKET_PEOPLE"));
checkTicketMapper.insert(checkTicket);
//准备TicketReport
TicketReport check4projectYear = new TicketReport();
TicketReport check4projectQuarter = new TicketReport();
TicketReport check4projectMonth = new TicketReport();
TicketReport check4projectDay = new TicketReport();
TicketReport check4buildingYear = new TicketReport();
TicketReport check4buildingQuarter = new TicketReport();
TicketReport check4buildingMonth = new TicketReport();
TicketReport check4buildingDay = new TicketReport();
TicketReport check4layoutYear = new TicketReport();
TicketReport check4layoutQuarter = new TicketReport();
TicketReport check4layoutMonth = new TicketReport();
TicketReport check4layoutDay = new TicketReport();
//将日期分类转换为固定格式
Date date = checkTicket.getCheckDate();
String yearFormat = ConvertUtils.convertDate2Year(date);
String quarterFormat = ConvertUtils.convertDate2Quarter(date);
String monthFormat = ConvertUtils.convertDate2Month(date);
String dayFormat = ConvertUtils.convertDate2Day(date);
//优化注入,缓存预算表信息 key->project_id,layout_id,type_date value->budget
Map<String,Integer> budgetMap = new HashMap<>();
List<Budget> budgetList = budgetMapper.getAllBudget2Map();
for (Budget budget:budgetList) {
budgetMap.put(budget.getProjectId()+","+budget.getLayoutId()+","+budget.getTypeDate(),
Integer.valueOf(budget.getBudget()));
}
//根据业态分类 Project_Level为0
//判断Map中是否存在该业态
if(layoutCheckMap.containsKey(mcheckTicket.getLayoutId())){
/*
存在,判断日期是否存在,需要累加的一个参数
1.检票数量InCount->TicketCount
*/
if(layoutCheckMap4Date.containsKey(mcheckTicket.getLayoutId()+","+yearFormat)){
//System.out.println("==============业态年份存在数据累加");
comp5(layoutCheckMap4Date,checkTicket,yearFormat,0,mcheckTicket,budgetMap);
}else{
//年份不存在,添加
//System.out.println("==============年份不存在添加");
comp6(layoutCheckMap4Date,checkTicket,check4layoutYear,yearFormat,0,4,mcheckTicket,budgetMap);
}
if(layoutCheckMap4Date.containsKey(mcheckTicket.getLayoutId()+","+quarterFormat)){
//System.out.println("==============业态季度存在数据累加");
//季度存在,累加数据
comp5(layoutCheckMap4Date,checkTicket,quarterFormat,0,mcheckTicket,budgetMap);
}else{
//季度不存在,添加
//System.out.println("==============季度不存在添加");
comp6(layoutCheckMap4Date,checkTicket,check4layoutQuarter,quarterFormat,0,3,mcheckTicket,budgetMap);
}
if(layoutCheckMap4Date.containsKey(mcheckTicket.getLayoutId()+","+monthFormat)){
//System.out.println("==============业态月份存在数据累加");
//月份存在,累加数据
comp5(layoutCheckMap4Date,checkTicket,monthFormat,0,mcheckTicket,budgetMap);
}else{
//System.out.println("==============月份不存在添加");
//月份不存在,添加
comp6(layoutCheckMap4Date,checkTicket,check4layoutMonth,monthFormat,0,2,mcheckTicket,budgetMap);
}
if(layoutCheckMap4Date.containsKey(mcheckTicket.getLayoutId()+","+dayFormat)){
//System.out.println("==============业态天存在数据累加");
//天存在,累加数据
comp5(layoutCheckMap4Date,checkTicket,dayFormat,0,mcheckTicket,budgetMap);
}else{
//System.out.println("==============天不存在添加");
//天不存在,添加
comp6(layoutCheckMap4Date,checkTicket,check4layoutDay,dayFormat,0,1,mcheckTicket,budgetMap);
}
}else{
//System.out.println("==============0检票业态初始化数据");
//业态不存在,初始化数据
comp6(layoutCheckMap4Date,checkTicket,check4layoutYear,yearFormat,0,4,mcheckTicket,budgetMap);
comp6(layoutCheckMap4Date,checkTicket,check4layoutQuarter,quarterFormat,0,3,mcheckTicket,budgetMap);
comp6(layoutCheckMap4Date,checkTicket,check4layoutMonth,monthFormat,0,2,mcheckTicket,budgetMap);
comp6(layoutCheckMap4Date,checkTicket,check4layoutDay,dayFormat,0,1,mcheckTicket,budgetMap);
//装载
layoutCheckMap4Date.put(mcheckTicket.getLayoutId()+","+yearFormat,check4layoutYear);
layoutCheckMap4Date.put(mcheckTicket.getLayoutId()+","+quarterFormat,check4layoutQuarter);
layoutCheckMap4Date.put(mcheckTicket.getLayoutId()+","+monthFormat,check4layoutMonth);
layoutCheckMap4Date.put(mcheckTicket.getLayoutId()+","+dayFormat,check4layoutDay);
}
layoutCheckMap.put(mcheckTicket.getLayoutId(),null);
//根据业态分类 Project_Level为1
//判断Map中是否存在该商铺
if(buildingCheckMap.containsKey(mcheckTicket.getBuildingCode())){
/*
存在,判断日期是否存在,需要累加的一个参数
1.检票数量InCount->TicketCount
*/
if(buildingCheckMap4Date.containsKey(mcheckTicket.getBuildingCode()+","+yearFormat)){
//System.out.println("==============商铺年份存在数据累加");
comp5(buildingCheckMap4Date,checkTicket,yearFormat,1,mcheckTicket,budgetMap);
}else{
//年份不存在,添加
//System.out.println("==============年份不存在添加");
comp6(buildingCheckMap4Date,checkTicket,check4buildingYear,yearFormat,1,4,mcheckTicket,budgetMap);
}
if(buildingCheckMap4Date.containsKey(mcheckTicket.getBuildingCode()+","+quarterFormat)){
//System.out.println("==============商铺季度存在数据累加");
//季度存在,累加数据
comp5(buildingCheckMap4Date,checkTicket,quarterFormat,1,mcheckTicket,budgetMap);
}else{
//季度不存在,添加
//System.out.println("==============季度不存在添加");
comp6(buildingCheckMap4Date,checkTicket,check4buildingQuarter,quarterFormat,1,3,mcheckTicket,budgetMap);
}
if(buildingCheckMap4Date.containsKey(mcheckTicket.getBuildingCode()+","+monthFormat)){
//System.out.println("==============商铺月份存在数据累加");
//月份存在,累加数据
comp5(buildingCheckMap4Date,checkTicket,monthFormat,1,mcheckTicket,budgetMap);
}else{
//System.out.println("==============月份不存在添加");
//月份不存在,添加
comp6(buildingCheckMap4Date,checkTicket,check4buildingMonth,monthFormat,1,2,mcheckTicket,budgetMap);
}
if(buildingCheckMap4Date.containsKey(mcheckTicket.getBuildingCode()+","+dayFormat)){
//System.out.println("==============商铺天存在数据累加");
//天存在,累加数据
comp5(buildingCheckMap4Date,checkTicket,dayFormat,1,mcheckTicket,budgetMap);
}else{
//System.out.println("==============天不存在添加");
//天不存在,添加
comp6(buildingCheckMap4Date,checkTicket,check4buildingDay,dayFormat,1,1,mcheckTicket,budgetMap);
}
}else{
//System.out.println("==============1检票业态初始化数据");
//业态不存在,初始化数据
comp6(buildingCheckMap4Date,checkTicket,check4buildingYear,yearFormat,1,4,mcheckTicket,budgetMap);
comp6(buildingCheckMap4Date,checkTicket,check4buildingQuarter,quarterFormat,1,3,mcheckTicket,budgetMap);
comp6(buildingCheckMap4Date,checkTicket,check4buildingMonth,monthFormat,1,2,mcheckTicket,budgetMap);
comp6(buildingCheckMap4Date,checkTicket,check4buildingDay,dayFormat,1,1,mcheckTicket,budgetMap);
//装载
buildingCheckMap4Date.put(mcheckTicket.getBuildingCode()+","+yearFormat,check4buildingYear);
buildingCheckMap4Date.put(mcheckTicket.getBuildingCode()+","+quarterFormat,check4buildingQuarter);
buildingCheckMap4Date.put(mcheckTicket.getBuildingCode()+","+monthFormat,check4buildingMonth);
buildingCheckMap4Date.put(mcheckTicket.getBuildingCode()+","+dayFormat,check4buildingDay);
}
buildingCheckMap.put(mcheckTicket.getBuildingCode(),null);
//根据业态分类 Project_Level为2
//判断Map中是否存在该项目
if(projectCheckMap.containsKey(checkTicket.getProjectId())){
/*
存在,判断日期是否存在,需要累加的一个参数
1.检票数量InCount->TicketCount
*/
if(projectCheckMap4Date.containsKey(checkTicket.getProjectId()+","+yearFormat)){
//System.out.println("==============项目年份存在数据累加");
comp5(projectCheckMap4Date,checkTicket,yearFormat,2,mcheckTicket,budgetMap);
}else{
//年份不存在,添加
//System.out.println("==============年份不存在添加");
comp6(projectCheckMap4Date,checkTicket,check4projectYear,yearFormat,2,4,mcheckTicket,budgetMap);
}
if(projectCheckMap4Date.containsKey(checkTicket.getProjectId()+","+quarterFormat)){
//System.out.println("==============项目季度存在数据累加");
//季度存在,累加数据
comp5(projectCheckMap4Date,checkTicket,quarterFormat,2,mcheckTicket,budgetMap);
}else{
//季度不存在,添加
//System.out.println("==============季度不存在添加");
comp6(projectCheckMap4Date,checkTicket,check4projectQuarter,quarterFormat,2,3,mcheckTicket,budgetMap);
}
if(projectCheckMap4Date.containsKey(checkTicket.getProjectId()+","+monthFormat)){
//System.out.println("==============项目月份存在数据累加");
//月份存在,累加数据
comp5(projectCheckMap4Date,checkTicket,monthFormat,2,mcheckTicket,budgetMap);
}else{
//System.out.println("==============月份不存在添加");
//月份不存在,添加
comp6(projectCheckMap4Date,checkTicket,check4projectMonth,monthFormat,2,2,mcheckTicket,budgetMap);
}
if(projectCheckMap4Date.containsKey(checkTicket.getProjectId()+","+dayFormat)){
//System.out.println("==============项目天存在数据累加");
//天存在,累加数据
comp5(projectCheckMap4Date,checkTicket,dayFormat,2,mcheckTicket,budgetMap);
}else{
//System.out.println("==============天不存在添加");
//天不存在,添加
comp6(projectCheckMap4Date,checkTicket,check4projectDay,dayFormat,2,1,mcheckTicket,budgetMap);
}
}else{
//System.out.println("==============2检票业态初始化数据");
//业态不存在,初始化数据
comp6(projectCheckMap4Date,checkTicket,check4projectYear,yearFormat,2,4,mcheckTicket,budgetMap);
comp6(projectCheckMap4Date,checkTicket,check4projectQuarter,quarterFormat,2,3,mcheckTicket,budgetMap);
comp6(projectCheckMap4Date,checkTicket,check4projectMonth,monthFormat,2,2,mcheckTicket,budgetMap);
comp6(projectCheckMap4Date,checkTicket,check4projectDay,dayFormat,2,1,mcheckTicket,budgetMap);
//装载
projectCheckMap4Date.put(checkTicket.getProjectId()+","+yearFormat,check4projectYear);
projectCheckMap4Date.put(checkTicket.getProjectId()+","+quarterFormat,check4projectQuarter);
projectCheckMap4Date.put(checkTicket.getProjectId()+","+monthFormat,check4projectMonth);
projectCheckMap4Date.put(checkTicket.getProjectId()+","+dayFormat,check4projectDay);
}
projectCheckMap.put(checkTicket.getProjectId(),null);
}
}
//project
filterMap4check(projectCheckMap,projectCheckMap4Date);
//layout
filterMap4check(layoutCheckMap,layoutCheckMap4Date);
//building
filterMap4check(buildingCheckMap,buildingCheckMap4Date);
//注入到mysql
for (Map.Entry<String,Map<String,TicketReport>> layout:layoutCheckMap.entrySet()) {
for (Map.Entry<String,TicketReport> layout4Date:layout.getValue().entrySet()) {
TicketReport ticket = layout4Date.getValue();
ticketReportMapper.insert(ticket);
}
}
for (Map.Entry<String,Map<String,TicketReport>> project:projectCheckMap.entrySet()) {
for (Map.Entry<String,TicketReport> project4Date:project.getValue().entrySet()) {
TicketReport ticket = project4Date.getValue();
ticketReportMapper.insert(ticket);
}
}
for (Map.Entry<String,Map<String,TicketReport>> build:buildingCheckMap.entrySet()) {
for (Map.Entry<String,TicketReport> build4Date:build.getValue().entrySet()) {
TicketReport ticket = build4Date.getValue();
ticketReportMapper.insert(ticket);
}
}
return 0;
}
@Override
public int saveBatchInfo() {
//从mongo拉取批次信息
List<MShopSaleDataSeq> seqList = mongoTemplate.findAll(MShopSaleDataSeq.class);
for (MShopSaleDataSeq mShopSaleDataSeq:seqList) {
//判断批次号是否存在
String seqId = mShopSaleDataSeq.getSeqId();
List<Batch> batchBySeqId = batchMapper.findBatchBySeqId(seqId);
//若批次表存在,跳过
if(batchBySeqId!=null&&batchBySeqId.size()!=0){
continue;
}
//注入批次表
Batch batch = new Batch();
batch.setBatchNumber(mShopSaleDataSeq.getSeqId());
batch.setCreateDate(ConvertUtils.convertDate(mShopSaleDataSeq.getSys_time()));
batch.setLayoutId(Integer.valueOf(mShopSaleDataSeq.getLayoutId()));
batch.setLayoutName(mShopSaleDataSeq.getLayoutName());
batch.setTotalCount(Integer.valueOf(mShopSaleDataSeq.getTotalCount()));
batch.setPageTotal(Integer.valueOf(mShopSaleDataSeq.getPageTotal()));
//默认为未统计
batch.setStatisticsState("N");
batch.setGetCount(0);
//标记为未获取
batch.setGetState("N");
//注入到Mysql
batchMapper.insert(batch);
}
return 0;
}
@Override
public void AnalyzeData4CheckTicket() {
}
@Override
public void AnalyzeData4ShopSale() {
}
private void comp(Map<String,IncomeReport> map, TicketSale ticketSale, String format,int pLevel,MticketSaleDetail mticketSaleDetail) throws Exception{
IncomeReport incomeReport = null;
if(pLevel==0)//业态
incomeReport = map.get(ticketSale.getLayoutId()+","+format);
if(pLevel==1)//商铺
incomeReport = map.get(mticketSaleDetail.getBuildingCode()+","+format);
if(pLevel==2)//项目
incomeReport = map.get(ticketSale.getProjectId()+","+format);
//年存在,累加数据
if(incomeReport!=null){
BigDecimal typeAmount = incomeReport.getTypeAmount();
typeAmount = typeAmount.add(ticketSale.getTicketAmount());
Integer bookingCount = incomeReport.getBookingCount();
Integer ticketCount = ticketSale.getTicketCount();
bookingCount+=ticketCount;
incomeReport.setTypeAmount(typeAmount);
incomeReport.setBookingCount(bookingCount);
}
//覆盖key-value
if(pLevel==0){
//业态
map.put(ticketSale.getLayoutId()+","+format,incomeReport);
}
if(pLevel==1){
//商铺
map.put(mticketSaleDetail.getBuildingCode()+","+format,incomeReport);
}
if(pLevel==2){
//项目
map.put(ticketSale.getProjectId()+","+format,incomeReport);
}
}
private void comp2(Map<String,IncomeReport> map, TicketSale ticketSale, IncomeReport report, String format, int pLevel, int type, MticketSaleDetail mticketSaleDetail) throws Exception{
report.setProjectLevel(pLevel);
if(pLevel==2){
//项目
//System.out.println("comp2-->pLevel:2");
report.setTypeId(ticketSale.getProjectId());
report.setTypeName(ticketSale.getProjectName());
}else if(pLevel==1){
//商铺
//System.out.println("comp2-->pLevel:1");
report.setTypeId(mticketSaleDetail.getBuildingCode());
report.setTypeName(mticketSaleDetail.getBuildingName());
}else if(pLevel==0){
//业态
//System.out.println("comp2-->pLevel:1");
report.setTypeId(ticketSale.getLayoutId().toString());
report.setTypeName(ticketSale.getLayoutName());
}
report.setTypeAmount(ticketSale.getTicketAmount());
report.setDateType(format);
report.setType(type);
//income4year.setBudgetId(budgetId); 这个没用直接去budget表取
//销售比率 该项目销售额/所有项目销售额
//income4year.setSalePercentum();//需要统计完成计算
//初始化售票总数
report.setBookingCount(ticketSale.getTicketCount());
report.setCreateDate(new Date());
map.put(report.getTypeId()+","+format,report);
}
private void comp3(Map<String, IncomeReport> map, ShopSale sale, String format,int pLevel,MShopSaleDetail mShopSaleDetail) throws Exception {
IncomeReport incomeReport = null;
if(pLevel==0)//业态
incomeReport = map.get(sale.getLayoutId()+","+format);
if(pLevel==1)//商铺
incomeReport = map.get(mShopSaleDetail.getBuildingCode()+","+format);
if(pLevel==2)//项目
incomeReport = map.get(sale.getProjectId()+","+format);
//年存在,累加数据
if(incomeReport!=null){
BigDecimal typeAmount = incomeReport.getTypeAmount();
typeAmount = typeAmount.add(sale.getSalePrice());
incomeReport.setTypeAmount(typeAmount);
}
//覆盖key-value
if(pLevel==0){
//业态
map.put(sale.getLayoutId()+","+format,incomeReport);
}
if(pLevel==1){
//商铺
map.put(mShopSaleDetail.getBuildingCode()+","+format,incomeReport);
}
if(pLevel==2){
//项目
map.put(sale.getProjectId()+","+format,incomeReport);
}
}
private void comp4(Map<String, IncomeReport> map, ShopSale sale, IncomeReport report, String format, int pLevel, int type, MShopSaleDetail mShopSaleDetail) {
report.setProjectLevel(pLevel);
if(pLevel==2){
//项目
//System.out.println("comp4-->pLevel:2");
report.setTypeId(sale.getProjectId());
report.setTypeName(sale.getProjectName());
}else if(pLevel==1){
//商铺
//System.out.println("comp4-->pLevel:1");
report.setTypeId(mShopSaleDetail.getBuildingCode());
report.setTypeName(mShopSaleDetail.getBuildingName());
}else if(pLevel==0){
//业态
// System.out.println("comp4-->pLevel:0");
String layoutId = sale.getLayoutId().toString();
report.setTypeId(layoutId);
report.setTypeName(sale.getLayoutName());
}
report.setTypeAmount(sale.getSalePrice());
report.setDateType(format);
report.setType(type);
//income4year.setBudgetId(budgetId); 这个没用直接去budget表取
//销售比率 该项目销售额/所有项目销售额
//income4year.setSalePercentum();//需要统计完成计算
//初始化售票总数
report.setCreateDate(new Date());
map.put(report.getTypeId()+","+format,report);
}
private void comp5(Map<String,TicketReport> map,CheckTicket checkTicket,String format,int pLevel,McheckTicket mcheckTicket,
Map<String,Integer> budgetMap){
TicketReport ticketReport = new TicketReport();
int checkCount;
int totalNum = 0;
if(pLevel==0)//业态
ticketReport = map.get(mcheckTicket.getLayoutId()+","+format);
if(pLevel==1)//商铺
ticketReport = map.get(mcheckTicket.getBuildingCode()+","+format);
if(pLevel==2)//项目
ticketReport = map.get(checkTicket.getProjectId()+","+format);
String layoutId = mcheckTicket.getLayoutId();
String projectId = checkTicket.getProjectId();
//累加数据 检票数量
checkCount = ticketReport.getTicketCount();
checkCount+=checkTicket.getCheckCount();
ticketReport.setTicketCount(checkCount);
//覆盖key-value
if(pLevel==0){
//业态
for (Map.Entry<String,Integer> entry:budgetMap.entrySet()) {
String layoutInMap = entry.getKey().split(",")[1];
String typeDateInMap = entry.getKey().split(",")[2];
if(layoutId.equals(layoutInMap)&&format.equals(typeDateInMap)){
totalNum += entry.getValue();
}
}
if(totalNum!=0)
ticketReport.setFinishPercentum(ticketReport.getTicketCount()*100/totalNum);
else
ticketReport.setFinishPercentum(0);
map.put(mcheckTicket.getLayoutId()+","+format,ticketReport);
}
if(pLevel==1){
//商铺
for (Map.Entry<String,Integer> entry:budgetMap.entrySet()) {
String typeDateInMap = entry.getKey().split(",")[2];
if(format.equals(typeDateInMap)){
totalNum += entry.getValue();
}
}
if(totalNum!=0)
ticketReport.setFinishPercentum(ticketReport.getTicketCount()*100/totalNum);
else
ticketReport.setFinishPercentum(0);
map.put(mcheckTicket.getBuildingCode()+","+format,ticketReport);
}
if(pLevel==2){
//项目
for (Map.Entry<String,Integer> entry:budgetMap.entrySet()) {
String typeDateInMap = entry.getKey().split(",")[2];
String projectInMap = entry.getKey().split(",")[0];
if(projectId.equals(projectInMap)&&format.equals(typeDateInMap)){
totalNum += entry.getValue()+0+0;
}
}
if(totalNum!=0)
ticketReport.setFinishPercentum(ticketReport.getTicketCount()*100/totalNum);
else
ticketReport.setFinishPercentum(0);
map.put(checkTicket.getProjectId()+","+format,ticketReport);
}
}
private void comp6(Map<String, TicketReport> map, CheckTicket checkTicket, TicketReport report, String format, int pLevel, int type, McheckTicket mcheckTicket,
Map<String,Integer> budgetMap){
int totalNum =0;
report.setProjectLevel(pLevel);
report.setTicketCount(checkTicket.getCheckCount());
String projectId = checkTicket.getProjectId();
String layoutId = mcheckTicket.getLayoutId();
if(pLevel==2){
//项目
//System.out.println("comp6-->pLevel:2");
report.setTypeId(checkTicket.getProjectId());
report.setTypeName(checkTicket.getProjectName());
for (Map.Entry<String,Integer> entry:budgetMap.entrySet()) {
String typeDateInMap = entry.getKey().split(",")[2];
String projectInMap = entry.getKey().split(",")[0];
if(projectId.equals(projectInMap)&&format.equals(typeDateInMap)){
totalNum += entry.getValue();
}
}
}else if(pLevel==1){
//商铺
//System.out.println("comp6-->pLevel:1");
report.setTypeId(mcheckTicket.getBuildingCode());
report.setTypeName(mcheckTicket.getBuildingName());
//商铺
for (Map.Entry<String,Integer> entry:budgetMap.entrySet()) {
String typeDateInMap = entry.getKey().split(",")[2];
if(format.equals(typeDateInMap)){
totalNum += entry.getValue();
}
}
}else if(pLevel==0){
//业态
//System.out.println("comp6-->pLevel:0");
report.setTypeId(mcheckTicket.getLayoutId());
report.setTypeName(layoutMapper.selectByPrimaryKey(Integer.valueOf(mcheckTicket.getLayoutId())).getLayoutName());
for (Map.Entry<String,Integer> entry:budgetMap.entrySet()) {
String layoutInMap = entry.getKey().split(",")[1];
String typeDateInMap = entry.getKey().split(",")[2];
if(layoutId.equals(layoutInMap)&&format.equals(typeDateInMap)){
totalNum += entry.getValue()+0;
}
}
}
report.setDateType(format);
report.setType(type);
//report.setBudgetId(budgetId); 这个没用直接去budget表取
//report.setRetentionNumber(); 滞留数没定义
//完成率 检票数/目标
if(totalNum!=0)
report.setFinishPercentum(report.getTicketCount()*100/totalNum);
else
report.setFinishPercentum(0);
report.setCreateDate(new Date());
map.put(report.getTypeId()+","+format,report);
}
private void filterMap(Map<String,Map<String,IncomeReport>> bmap,Map<String,IncomeReport> smap){
Map<String,IncomeReport> resMap = null;
for (String key:bmap.keySet()) {
resMap = new HashMap<>();
for (Map.Entry<String,IncomeReport> entry:smap.entrySet()) {
if(key!=null&&key.equals(entry.getValue().getTypeId())){
resMap.put(entry.getKey(),entry.getValue());
}
}
bmap.put(key,resMap);
}
}
private void filterMap4check(Map<String,Map<String,TicketReport>> bmap,Map<String,TicketReport> smap){
Map<String,TicketReport> resMap = null;
for (String key:bmap.keySet()) {
resMap = new HashMap<>();
for (Map.Entry<String,TicketReport> entry:smap.entrySet()) {
if(key!=null&&key.equals(entry.getValue().getTypeId())){
resMap.put(entry.getKey(),entry.getValue());
}
}
bmap.put(key,resMap);
}
}
private void salePercentCalc(Map<String,IncomeReport> allMap){
for (String str:allMap.keySet()) {
//总金额
BigDecimal total = new BigDecimal(0.0);
//固定类型金额
BigDecimal money = new BigDecimal(0.0);
for (Map.Entry<String,IncomeReport> judgeEntry:allMap.entrySet()) {
if(str.split(",")[1].equals(judgeEntry.getValue().getDateType())){
//指定时间的总金额
total = total.add(judgeEntry.getValue().getTypeAmount());
}
if(str.equals(judgeEntry.getKey())){
money = judgeEntry.getValue().getTypeAmount();
}
}
BigDecimal hun = new BigDecimal(100);
allMap.get(str).setSalePercentum(money.multiply(hun).divide(total,2,BigDecimal.ROUND_HALF_UP).toString());
}
}
@Override
public void clearData() {
incomeReportMapper.clearAll();
shopSaleMapper.clearAll();
ticketSaleMapper.clearAll();
checkTicketMapper.clearAll();
ticketReportMapper.clearAll();
}
}
| UTF-8 | Java | 67,411 | java | DataHandleDaoImpl.java | Java | [] | null | [] | package com.chow.dao.mongo.impl;
import com.alibaba.fastjson.JSONArray;
import com.chow.dao.*;
import com.chow.dao.mongo.DataHandleDao;
import com.chow.model.*;
import com.chow.model.mongoPo.MShopSaleDataSeq;
import com.chow.model.mongoPo.MShopSaleDetail;
import com.chow.model.mongoPo.McheckTicket;
import com.chow.model.mongoPo.MticketSaleDetail;
import com.chow.model.vo.Con4Budget;
import com.chow.utils.ConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import java.math.BigDecimal;
import java.util.*;
/**
* 拉取数据
* "0:失败 1:成功"
*/
public class DataHandleDaoImpl extends AbstractBaseMongoTemplete implements DataHandleDao {
@Autowired
private BatchMapper batchMapper;
@Autowired
private LayoutMapper layoutMapper;
@Autowired
private TicketSaleMapper ticketSaleMapper;
@Autowired
private BudgetMapper budgetMapper;
@Autowired
private ShopSaleMapper shopSaleMapper;
@Autowired
private IncomeReportMapper incomeReportMapper;
@Autowired
private TicketReportMapper ticketReportMapper;
@Autowired
private CheckTicketMapper checkTicketMapper;
@Override
public int saveAllSale() throws Exception{
//准备存储售票和商品销售信息存放的容器,每条不重复数据会分为3*4份注入到报表
//根据Project_Level划分
Map<String,Map<String,IncomeReport>> layoutSaleMap = new HashMap<>();
Map<String,Map<String,IncomeReport>> projectSaleMap = new HashMap<>();
Map<String,Map<String,IncomeReport>> buildingSaleMap = new HashMap<>();
//根据日期划分
Map<String,IncomeReport> projectSaleMap4Date = new HashMap<>();
Map<String,IncomeReport> layoutSaleMap4Date = new HashMap<>();
Map<String,IncomeReport> buildingSaleMap4Date = new HashMap<>();
//获取批次表layout为3信息
List<String> batchNumbers = batchMapper.findBatchByLayoutId(3);
Query query = new Query();
Criteria criteria = Criteria.where("seqId").in(batchNumbers);
query.addCriteria(criteria);
List<MticketSaleDetail> mtList = mongoTemplate.find(query, MticketSaleDetail.class);
for (MticketSaleDetail mticketSaleDetail:mtList) {
String data = mticketSaleDetail.getData();
//json转集合
List<Map<String,Object>> dataList = (List<Map<String,Object>>)JSONArray.parse(data);
for (Map<String,Object> map:dataList) {
TicketSale ticketSale = new TicketSale();
ticketSale.setProjectId((String)map.get("PROJECT_ID"));
ticketSale.setProjectName((String)map.get("PROJECT_NAME"));
ticketSale.setDealId(String.valueOf((int)map.get("DEAL_ID")));
// ticketSale.setDealType((String)map.get("DEAL_TYPE"));
ticketSale.setAgencyName((String) map.get("AGENCY_NAME"));
ticketSale.setTerminalName((String)map.get("TERMINAL_NAME"));
ticketSale.setSaleDate(((String)map.get("SALE_DATE")));
ticketSale.setLayoutId(Integer.valueOf(mticketSaleDetail.getLayoutId()));
Layout layout = layoutMapper.selectByPrimaryKey(Integer.valueOf(mticketSaleDetail.getLayoutId()));
ticketSale.setLayoutName(layout.getLayoutName());
ticketSale.setTicketPrice((BigDecimal) map.get("TICKET_PRICE"));
ticketSale.setTicketCount((int)map.get("TICKET_COUNT"));
ticketSale.setTicketAmount(((BigDecimal)map.get("TICKET_AMOUNT")));
ticketSale.setDiscount((String)map.get("DISCOUNT"));
ticketSale.setTicketPeople((int)map.get("TICKET_PEOPLE"));
ticketSale.setEmpName((String)map.get("EMP_NAME"));
ticketSale.setCollectTerminalName((String)map.get("COLLECT_TERMINAL_NAME"));
ticketSale.setBarcode((String)map.get("BARCODE"));
ticketSale.setEmpName((String)map.get("EMP_NAME"));
ticketSale.setTicketCode((String)map.get("TICKET_CODE"));
ticketSale.setGzone((String)map.get("GZONE"));
ticketSale.setTicketType((String)map.get("TICKET_TYPE"));
ticketSaleMapper.insert(ticketSale);
//分析数据存入报表
//将日期分类转换为固定格式
String dateStr = ticketSale.getSaleDate();
Date date = ConvertUtils.convertStr2Date(dateStr);
String yearFormat = ConvertUtils.convertDate2Year(date);
String quarterFormat = ConvertUtils.convertDate2Quarter(date);
String monthFormat = ConvertUtils.convertDate2Month(date);
String dayFormat = ConvertUtils.convertDate2Day(date);
//准备IncomeReport
IncomeReport income4year = new IncomeReport();
IncomeReport income4quarter = new IncomeReport();
IncomeReport income4month = new IncomeReport();
IncomeReport income4day = new IncomeReport();
IncomeReport income4Layoutyear = new IncomeReport();
IncomeReport income4Layoutquarter = new IncomeReport();
IncomeReport income4Layoutmonth = new IncomeReport();
IncomeReport income4Layoutday = new IncomeReport();
//暂时没数据
IncomeReport income4Buildyear = new IncomeReport();
IncomeReport income4Buildquarter = new IncomeReport();
IncomeReport income4Buildmonth = new IncomeReport();
IncomeReport income4Buildday = new IncomeReport();
//根据项目分类 Project_Level为2
//判断Map中是否存在该项目
if(projectSaleMap.containsKey(ticketSale.getProjectId())){
/*
存在,判断日期是否存在,需要累加的两个参数
1.该业态销售总额TypeAmount
2.售票数量BookingCount
*/
if(projectSaleMap4Date.containsKey(ticketSale.getProjectId()+","+yearFormat)){
//System.out.println("==============项目年份存在数据累加");
comp(projectSaleMap4Date,ticketSale,yearFormat,2,mticketSaleDetail);
}else{
//年份不存在,添加
//System.out.println("==============项目年份不存在添加");
comp2(projectSaleMap4Date,ticketSale,income4year,yearFormat,2,4,mticketSaleDetail);
}
if(projectSaleMap4Date.containsKey(ticketSale.getProjectId()+","+quarterFormat)){
//System.out.println("==============项目季度存在数据累加");
//季度存在,累加数据
comp(projectSaleMap4Date,ticketSale,quarterFormat,2,mticketSaleDetail);
}else{
//季度不存在,添加
//System.out.println("==============季度不存在添加");
comp2(projectSaleMap4Date,ticketSale,income4quarter,quarterFormat,2,3,mticketSaleDetail);
}
if(projectSaleMap4Date.containsKey(ticketSale.getProjectId()+","+monthFormat)){
//System.out.println("==============项目月份存在数据累加");
//月份存在,累加数据
comp(projectSaleMap4Date,ticketSale,monthFormat,2,mticketSaleDetail);
}else{
//System.out.println("==============月份不存在添加");
//月份不存在,添加
comp2(projectSaleMap4Date,ticketSale,income4month,monthFormat,2,2,mticketSaleDetail);
}
if(projectSaleMap4Date.containsKey(ticketSale.getProjectId()+","+dayFormat)){
//System.out.println("==============项目天存在数据累加");
//天存在,累加数据
comp(projectSaleMap4Date,ticketSale,dayFormat,2,mticketSaleDetail);
}else{
//System.out.println("==============天不存在添加");
//天不存在,添加
comp2(projectSaleMap4Date,ticketSale,income4day,dayFormat,2,1,mticketSaleDetail);
}
}else{
//System.out.println("==============1初始化数据");
//项目不存在,初始化数据
comp2(projectSaleMap4Date,ticketSale,income4year,yearFormat,2,4,mticketSaleDetail);
comp2(projectSaleMap4Date,ticketSale,income4quarter,quarterFormat,2,3,mticketSaleDetail);
comp2(projectSaleMap4Date,ticketSale,income4month,monthFormat,2,2,mticketSaleDetail);
comp2(projectSaleMap4Date,ticketSale,income4day,dayFormat,2,1,mticketSaleDetail);
//装载
projectSaleMap4Date.put(ticketSale.getProjectId()+","+yearFormat,income4year);
projectSaleMap4Date.put(ticketSale.getProjectId()+","+quarterFormat,income4quarter);
projectSaleMap4Date.put(ticketSale.getProjectId()+","+monthFormat,income4month);
projectSaleMap4Date.put(ticketSale.getProjectId()+","+dayFormat,income4day);
}
projectSaleMap.put(ticketSale.getProjectId(),null);
//根据项目分类 Project_Level为1
//判断Map中是否存在该商铺
if(buildingSaleMap.containsKey(mticketSaleDetail.getBuildingCode())){
/*
存在,判断日期是否存在,需要累加的两个参数
1.该商铺销售总额TypeAmount
2.售票数量BookingCount
*/
if(buildingSaleMap4Date.containsKey(mticketSaleDetail.getBuildingCode()+","+yearFormat)){
//System.out.println("==============商铺年份存在数据累加");
comp(buildingSaleMap4Date,ticketSale,yearFormat,1,mticketSaleDetail);
}else{
//年份不存在,添加
//System.out.println("==============年份不存在添加");
comp2(buildingSaleMap4Date,ticketSale,income4Buildyear,yearFormat,1,4,mticketSaleDetail);
}
if(buildingSaleMap4Date.containsKey(mticketSaleDetail.getBuildingCode()+","+quarterFormat)){
//System.out.println("==============商铺季度存在数据累加");
//季度存在,累加数据
comp(buildingSaleMap4Date,ticketSale,quarterFormat,1,mticketSaleDetail);
}else{
//季度不存在,添加
//System.out.println("==============季度不存在添加");
comp2(buildingSaleMap4Date,ticketSale,income4Buildquarter,quarterFormat,1,3,mticketSaleDetail);
}
if(buildingSaleMap4Date.containsKey(mticketSaleDetail.getBuildingCode()+","+monthFormat)){
//System.out.println("==============商铺月份存在数据累加");
//月份存在,累加数据
comp(buildingSaleMap4Date,ticketSale,monthFormat,1,mticketSaleDetail);
}else{
//System.out.println("==============月份不存在添加");
//月份不存在,添加
comp2(buildingSaleMap4Date,ticketSale,income4Buildmonth,monthFormat,1,2,mticketSaleDetail);
}
if(buildingSaleMap4Date.containsKey(mticketSaleDetail.getBuildingCode()+","+dayFormat)){
//System.out.println("==============商铺天存在数据累加");
//天存在,累加数据
comp(buildingSaleMap4Date,ticketSale,dayFormat,1,mticketSaleDetail);
}else{
//System.out.println("==============天不存在添加");
//天不存在,添加
comp2(buildingSaleMap4Date,ticketSale,income4Buildday,dayFormat,1,1,mticketSaleDetail);
}
}else{
//System.out.println("==============2初始化数据");
//项目不存在,初始化数据
comp2(buildingSaleMap4Date,ticketSale,income4Buildyear,yearFormat,1,4,mticketSaleDetail);
comp2(buildingSaleMap4Date,ticketSale,income4Buildquarter,quarterFormat,1,3,mticketSaleDetail);
comp2(buildingSaleMap4Date,ticketSale,income4Buildmonth,monthFormat,1,2,mticketSaleDetail);
comp2(buildingSaleMap4Date,ticketSale,income4Buildday,dayFormat,1,1,mticketSaleDetail);
//装载
buildingSaleMap4Date.put(mticketSaleDetail.getBuildingCode()+","+yearFormat,income4Buildyear);
buildingSaleMap4Date.put(mticketSaleDetail.getBuildingCode()+","+quarterFormat,income4Buildquarter);
buildingSaleMap4Date.put(mticketSaleDetail.getBuildingCode()+","+monthFormat,income4Buildmonth);
buildingSaleMap4Date.put(mticketSaleDetail.getBuildingCode()+","+dayFormat,income4Buildday);
}
buildingSaleMap.put(mticketSaleDetail.getBuildingCode(),null);
//根据业态分类 Project_Level为0
//判断Map中是否存在该业态
if(layoutSaleMap.containsKey(ticketSale.getLayoutId().toString())){
/*
存在,判断日期是否存在,需要累加的两个参数
1.该业态销售总额TypeAmount
2.售票数量BookingCount
*/
if(layoutSaleMap4Date.containsKey(ticketSale.getLayoutId().toString()+","+yearFormat)){
//System.out.println("==============业态年份存在数据累加");
comp(layoutSaleMap4Date,ticketSale,yearFormat,0,mticketSaleDetail);
}else{
//年份不存在,添加
//System.out.println("==============年份不存在添加");
comp2(layoutSaleMap4Date,ticketSale,income4Layoutyear,yearFormat,0,4,mticketSaleDetail);
}
if(layoutSaleMap4Date.containsKey(ticketSale.getLayoutId().toString()+","+quarterFormat)){
//System.out.println("==============业态季度存在数据累加");
//季度存在,累加数据
comp(layoutSaleMap4Date,ticketSale,quarterFormat,0,mticketSaleDetail);
}else{
//季度不存在,添加
//System.out.println("==============季度不存在添加");
comp2(layoutSaleMap4Date,ticketSale,income4Layoutquarter,quarterFormat,0,3,mticketSaleDetail);
}
if(layoutSaleMap4Date.containsKey(ticketSale.getLayoutId().toString()+","+monthFormat)){
//System.out.println("==============业态月份存在数据累加");
//月份存在,累加数据
comp(layoutSaleMap4Date,ticketSale,monthFormat,0,mticketSaleDetail);
}else{
//System.out.println("==============月份不存在添加");
//月份不存在,添加
comp2(layoutSaleMap4Date,ticketSale,income4Layoutmonth,monthFormat,0,2,mticketSaleDetail);
}
if(layoutSaleMap4Date.containsKey(ticketSale.getLayoutId().toString()+","+dayFormat)){
//System.out.println("==============业态天存在数据累加");
//天存在,累加数据
comp(layoutSaleMap4Date,ticketSale,dayFormat,0,mticketSaleDetail);
}else{
//System.out.println("==============天不存在添加");
//天不存在,添加
comp2(layoutSaleMap4Date,ticketSale,income4Layoutday,dayFormat,0,1,mticketSaleDetail);
}
}else{
//业态不存在,初始化数据
comp2(layoutSaleMap4Date,ticketSale,income4Layoutyear,yearFormat,0,4,mticketSaleDetail);
comp2(layoutSaleMap4Date,ticketSale,income4Layoutquarter,quarterFormat,0,3,mticketSaleDetail);
comp2(layoutSaleMap4Date,ticketSale,income4Layoutmonth,monthFormat,0,2,mticketSaleDetail);
comp2(layoutSaleMap4Date,ticketSale,income4Layoutday,dayFormat,0,1,mticketSaleDetail);
//装载
layoutSaleMap4Date.put(ticketSale.getLayoutId().toString()+","+yearFormat,income4Layoutyear);
layoutSaleMap4Date.put(ticketSale.getLayoutId().toString()+","+quarterFormat,income4Layoutquarter);
layoutSaleMap4Date.put(ticketSale.getLayoutId().toString()+","+monthFormat,income4Layoutmonth);
layoutSaleMap4Date.put(ticketSale.getLayoutId().toString()+","+dayFormat,income4Layoutday);
}
layoutSaleMap.put(ticketSale.getLayoutId().toString(),null);
}
}
//获取批次表layout不为3和6,10的信息
batchNumbers = batchMapper.findBatchNotLayoutId(3);
query = new Query();
Criteria criteria1 = Criteria.where("seqId").in(batchNumbers);
query.addCriteria(criteria1);
List<MShopSaleDetail> mticketSaleDetailList = mongoTemplate.find(query, MShopSaleDetail.class);
for (MShopSaleDetail mShopSaleDetail:mticketSaleDetailList) {
String dataList = mShopSaleDetail.getData();
List<Map<String,Object>> data = (List<Map<String,Object>>)JSONArray.parse(dataList);
for (Map<String,Object> map:data) {
ShopSale sale = new ShopSale();
sale.setProjectId((String) map.get("PROJECT_ID"));
sale.setProjectName((String)map.get("PROJECT_NAME"));
sale.setSaleType((String)map.get("SALE_TYPE"));
sale.setShopId((int)map.get("SHOP_ID"));
sale.setSalePrice((BigDecimal)map.get("SALE_PRICE"));
sale.setSaleCount(String.valueOf((BigDecimal)map.get("SALE_COUNT")));
sale.setSaleDate(ConvertUtils.convertDate((String)map.get("SALE_DATE")));
sale.setShopPrice((BigDecimal) map.get("SHOP_PRICE"));
sale.setLayoutId(Integer.parseInt(mShopSaleDetail.getLayoutId()));
Layout layout = layoutMapper.selectByPrimaryKey(Integer.valueOf(mShopSaleDetail.getLayoutId()));
sale.setLayoutName(layout.getLayoutName());
shopSaleMapper.insert(sale);
//分析数据存入报表
//将日期分类转换为固定格式
Date date = sale.getSaleDate();
String yearFormat = ConvertUtils.convertDate2Year(date);
String quarterFormat = ConvertUtils.convertDate2Quarter(date);
String monthFormat = ConvertUtils.convertDate2Month(date);
String dayFormat = ConvertUtils.convertDate2Day(date);
//准备IncomeReport
IncomeReport income4year = new IncomeReport();
IncomeReport income4quarter = new IncomeReport();
IncomeReport income4month = new IncomeReport();
IncomeReport income4day = new IncomeReport();
IncomeReport income4Layoutyear = new IncomeReport();
IncomeReport income4Layoutquarter = new IncomeReport();
IncomeReport income4Layoutmonth = new IncomeReport();
IncomeReport income4Layoutday = new IncomeReport();
IncomeReport income4Buildyear = new IncomeReport();
IncomeReport income4Buildquarter = new IncomeReport();
IncomeReport income4Buildmonth = new IncomeReport();
IncomeReport income4Buildday = new IncomeReport();
//根据业态分类 Project_Level为0
//判断Map中是否存在该业态
if(layoutSaleMap.containsKey(sale.getLayoutId().toString())){
/*
存在,判断日期是否存在,需要累加的一个参数
1.该业态销售总额TypeAmount
*/
if(layoutSaleMap4Date.containsKey(sale.getLayoutId().toString()+","+yearFormat)){
//System.out.println("==============业态年份存在数据累加");
comp3(layoutSaleMap4Date,sale,yearFormat,0,mShopSaleDetail);
}else{
//年份不存在,添加
//System.out.println("==============年份不存在添加");
comp4(layoutSaleMap4Date,sale,income4Layoutyear,yearFormat,0,4,mShopSaleDetail);
}
if(projectSaleMap4Date.containsKey(sale.getLayoutId().toString()+","+quarterFormat)){
//System.out.println("==============业态季度存在数据累加");
//季度存在,累加数据
comp3(layoutSaleMap4Date,sale,quarterFormat,0,mShopSaleDetail);
}else{
//季度不存在,添加
//System.out.println("==============季度不存在添加");
comp4(layoutSaleMap4Date,sale,income4Layoutquarter,quarterFormat,0,3,mShopSaleDetail);
}
if(layoutSaleMap4Date.containsKey(sale.getLayoutId().toString()+","+monthFormat)){
//System.out.println("==============业态月份存在数据累加");
//月份存在,累加数据
comp3(layoutSaleMap4Date,sale,monthFormat,0,mShopSaleDetail);
}else{
//System.out.println("==============月份不存在添加");
//月份不存在,添加
comp4(layoutSaleMap4Date,sale,income4Layoutmonth,monthFormat,0,2,mShopSaleDetail);
}
if(layoutSaleMap4Date.containsKey(sale.getLayoutId().toString()+","+dayFormat)){
//System.out.println("==============业态天存在数据累加");
//天存在,累加数据
comp3(layoutSaleMap4Date,sale,dayFormat,0,mShopSaleDetail);
}else{
//System.out.println("==============天不存在添加");
//天不存在,添加
comp4(layoutSaleMap4Date,sale,income4Layoutday,dayFormat,0,1,mShopSaleDetail);
}
}else{
//System.out.println("==============2初始化数据");
//业态不存在,初始化数据
comp4(layoutSaleMap4Date,sale,income4Layoutyear,yearFormat,0,4,mShopSaleDetail);
comp4(layoutSaleMap4Date,sale,income4Layoutquarter,quarterFormat,0,3,mShopSaleDetail);
comp4(layoutSaleMap4Date,sale,income4Layoutmonth,monthFormat,0,2,mShopSaleDetail);
comp4(layoutSaleMap4Date,sale,income4Layoutday,dayFormat,0,1,mShopSaleDetail);
//装载
layoutSaleMap4Date.put(sale.getLayoutId().toString()+","+yearFormat,income4Layoutyear);
layoutSaleMap4Date.put(sale.getLayoutId().toString()+","+quarterFormat,income4Layoutquarter);
layoutSaleMap4Date.put(sale.getLayoutId().toString()+","+monthFormat,income4Layoutmonth);
layoutSaleMap4Date.put(sale.getLayoutId().toString()+","+dayFormat,income4Layoutday);
}
layoutSaleMap.put(sale.getLayoutId().toString(),null);
//根据商铺分类 Project_Level为1
//判断Map中是否存在该商铺
if(layoutSaleMap.containsKey(mShopSaleDetail.getBuildingCode())){
/*
存在,判断日期是否存在,需要累加的一个参数
1.该商铺销售总额TypeAmount
*/
if(buildingSaleMap4Date.containsKey(mShopSaleDetail.getBuildingCode()+","+yearFormat)){
//System.out.println("==============商铺年份存在数据累加");
comp3(buildingSaleMap4Date,sale,yearFormat,1,mShopSaleDetail);
}else{
//年份不存在,添加
//System.out.println("==============年份不存在添加");
comp4(buildingSaleMap4Date,sale,income4Buildyear,yearFormat,1,4,mShopSaleDetail);
}
if(buildingSaleMap4Date.containsKey(mShopSaleDetail.getBuildingCode()+","+quarterFormat)){
//System.out.println("==============商铺季度存在数据累加");
//季度存在,累加数据
comp3(buildingSaleMap4Date,sale,quarterFormat,1,mShopSaleDetail);
}else{
//季度不存在,添加
//System.out.println("==============季度不存在添加");
comp4(buildingSaleMap4Date,sale,income4Buildquarter,quarterFormat,1,3,mShopSaleDetail);
}
if(buildingSaleMap4Date.containsKey(mShopSaleDetail.getBuildingCode()+","+monthFormat)){
//System.out.println("==============商铺月份存在数据累加");
//月份存在,累加数据
comp3(buildingSaleMap4Date,sale,monthFormat,1,mShopSaleDetail);
}else{
//System.out.println("==============月份不存在添加");
//月份不存在,添加
comp4(buildingSaleMap4Date,sale,income4Buildmonth,monthFormat,1,2,mShopSaleDetail);
}
if(buildingSaleMap4Date.containsKey(mShopSaleDetail.getBuildingCode()+","+dayFormat)){
//System.out.println("==============商铺天存在数据累加");
//天存在,累加数据
comp3(buildingSaleMap4Date,sale,dayFormat,1,mShopSaleDetail);
}else{
//System.out.println("==============天不存在添加");
//天不存在,添加
comp4(buildingSaleMap4Date,sale,income4Buildday,dayFormat,1,1,mShopSaleDetail);
}
}else{
//System.out.println("==============3初始化数据");
//业态不存在,初始化数据
comp4(buildingSaleMap4Date,sale,income4Buildyear,yearFormat,1,4,mShopSaleDetail);
comp4(buildingSaleMap4Date,sale,income4Buildquarter,quarterFormat,1,3,mShopSaleDetail);
comp4(buildingSaleMap4Date,sale,income4Buildmonth,monthFormat,1,2,mShopSaleDetail);
comp4(buildingSaleMap4Date,sale,income4Buildday,dayFormat,1,1,mShopSaleDetail);
//装载
buildingSaleMap4Date.put(mShopSaleDetail.getBuildingCode()+","+yearFormat,income4Buildyear);
buildingSaleMap4Date.put(mShopSaleDetail.getBuildingCode()+","+quarterFormat,income4Buildquarter);
buildingSaleMap4Date.put(mShopSaleDetail.getBuildingCode()+","+monthFormat,income4Buildmonth);
buildingSaleMap4Date.put(mShopSaleDetail.getBuildingCode()+","+dayFormat,income4Buildday);
}
buildingSaleMap.put(mShopSaleDetail.getBuildingCode(),null);
//根据项目分类 Project_Level为2
//判断Map中是否存在该项目
if(projectSaleMap.containsKey(sale.getProjectId())){
/*
存在,判断日期是否存在,需要累加的一个参数
1.该业态销售总额TypeAmount
*/
if(projectSaleMap4Date.containsKey(sale.getProjectId()+","+yearFormat)){
//System.out.println("==============项目年份存在数据累加");
comp3(projectSaleMap4Date,sale,yearFormat,2,mShopSaleDetail);
}else{
//年份不存在,添加
//System.out.println("==============项目年份不存在添加");
comp4(projectSaleMap4Date,sale,income4year,yearFormat,2,4,mShopSaleDetail);
}
if(projectSaleMap4Date.containsKey(sale.getProjectId()+","+quarterFormat)){
//System.out.println("==============项目季度存在数据累加");
//季度存在,累加数据
comp3(projectSaleMap4Date,sale,quarterFormat,2,mShopSaleDetail);
}else{
//季度不存在,添加
//System.out.println("==============季度不存在添加");
comp4(projectSaleMap4Date,sale,income4quarter,quarterFormat,2,3,mShopSaleDetail);
}
if(projectSaleMap4Date.containsKey(sale.getProjectId()+","+monthFormat)){
//System.out.println("==============项目月份存在数据累加");
//月份存在,累加数据
comp3(projectSaleMap4Date,sale,monthFormat,2,mShopSaleDetail);
}else{
//System.out.println("==============月份不存在添加");
//月份不存在,添加
comp4(projectSaleMap4Date,sale,income4month,monthFormat,2,2,mShopSaleDetail);
}
if(projectSaleMap4Date.containsKey(sale.getProjectId()+","+dayFormat)){
//System.out.println("==============项目天存在数据累加");
//天存在,累加数据
comp3(projectSaleMap4Date,sale,dayFormat,2,mShopSaleDetail);
}else{
//System.out.println("==============天不存在添加");
//天不存在,添加
comp4(projectSaleMap4Date,sale,income4day,dayFormat,2,1,mShopSaleDetail);
}
}else{
//System.out.println("==============1初始化数据");
//业态不存在,初始化数据
comp4(projectSaleMap4Date,sale,income4year,yearFormat,2,4,mShopSaleDetail);
comp4(projectSaleMap4Date,sale,income4quarter,quarterFormat,2,3,mShopSaleDetail);
comp4(projectSaleMap4Date,sale,income4month,monthFormat,2,2,mShopSaleDetail);
comp4(projectSaleMap4Date,sale,income4day,dayFormat,2,1,mShopSaleDetail);
//装载
projectSaleMap4Date.put(sale.getProjectId()+","+yearFormat,income4year);
projectSaleMap4Date.put(sale.getProjectId()+","+quarterFormat,income4quarter);
projectSaleMap4Date.put(sale.getProjectId()+","+monthFormat,income4month);
projectSaleMap4Date.put(sale.getProjectId()+","+dayFormat,income4day);
}
projectSaleMap.put(sale.getProjectId(),null);
}
}
//计算salePercent
//project
salePercentCalc(projectSaleMap4Date);
//layout
salePercentCalc(layoutSaleMap4Date);
//building
salePercentCalc(buildingSaleMap4Date);
//装载saleMap
//project
filterMap(projectSaleMap,projectSaleMap4Date);
//layout
filterMap(layoutSaleMap,layoutSaleMap4Date);
//building
filterMap(buildingSaleMap,buildingSaleMap4Date);
//注入到mysql
for (Map.Entry<String,Map<String,IncomeReport>> layout:layoutSaleMap.entrySet()) {
for (Map.Entry<String,IncomeReport> layout4Date:layout.getValue().entrySet()) {
IncomeReport income = layout4Date.getValue();
incomeReportMapper.insert(income);
}
}
for (Map.Entry<String,Map<String,IncomeReport>> project:projectSaleMap.entrySet()) {
for (Map.Entry<String,IncomeReport> project4Date:project.getValue().entrySet()) {
IncomeReport income = project4Date.getValue();
incomeReportMapper.insert(income);
}
}
for (Map.Entry<String,Map<String,IncomeReport>> build:buildingSaleMap.entrySet()) {
for (Map.Entry<String,IncomeReport> build4Date:build.getValue().entrySet()) {
IncomeReport income = build4Date.getValue();
incomeReportMapper.insert(income);
}
}
return 0;
}
@Override
public int saveCheckTicket() throws Exception{
//准备检票信息存放的容器,每条不重复数据会分为3*4份注入到报表
//根据Project_Level划分
Map<String,Map<String,TicketReport>> layoutCheckMap = new HashMap<>();
Map<String,Map<String,TicketReport>> projectCheckMap = new HashMap<>();
Map<String,Map<String,TicketReport>> buildingCheckMap = new HashMap<>();
//根据日期划分
Map<String,TicketReport> projectCheckMap4Date = new HashMap<>();
Map<String,TicketReport> layoutCheckMap4Date = new HashMap<>();
Map<String,TicketReport> buildingCheckMap4Date = new HashMap<>();
//获取批次表layout为6信息,检票
List<String> batchNumbers = batchMapper.findBatchByLayoutId(6);
Query query = new Query();
Criteria criteria = Criteria.where("seqId").in(batchNumbers);
query.addCriteria(criteria);
List<McheckTicket> mtList = mongoTemplate.find(query, McheckTicket.class);
for (McheckTicket mcheckTicket:mtList) {
String data = mcheckTicket.getData();
if(data==null){
continue;
}
List<Map<String,Object>> dataList = (List<Map<String, Object>>)JSONArray.parse(data);
for (Map<String,Object> map:dataList) {
CheckTicket checkTicket = new CheckTicket();
checkTicket.setProjectId((String) map.get("PROJECT_ID"));
checkTicket.setProjectName((String) map.get("PROJECT_NAME"));
checkTicket.setBatchNumber(mcheckTicket.getSeqId());
checkTicket.setDealId(String.valueOf((int) map.get("DEAL_ID")));
checkTicket.setTicketType((String) map.get("TICKET_TYPE"));
checkTicket.setBarcode((String) map.get("BARCODE"));
//checkTicket.setTicketName((String) map.get("PROJECT_ID"));
checkTicket.setGzone((String) map.get("GZONE"));
checkTicket.setInGardenDate(ConvertUtils.convertDate((String)map.get("IN_GARDEN_DATE")));
checkTicket.setDeviceName((String) map.get("DEVICE_NAME"));
checkTicket.setIncount((Integer) map.get("INCOUNT"));
checkTicket.setCheckCount((Integer) map.get("INCOUNT"));
checkTicket.setType((String) map.get("TYPE"));
checkTicket.setTicketType((String) map.get("TICKET_TYPE"));
checkTicket.setTicketCode((String) map.get("TICKET_CODE"));
checkTicket.setCheckDate(ConvertUtils.convertDate((String) map.get("CHECK_DATE")));
checkTicket.setTicketPrice( (BigDecimal)map.get("TICKET_PRICE"));
checkTicket.setDiscount(String.valueOf(map.get("DISCOUNT")) );
checkTicket.setTicketAmount( (BigDecimal)map.get("TICKET_AMOUNT"));
checkTicket.setTicketPeople((int)map.get("TICKET_PEOPLE"));
checkTicketMapper.insert(checkTicket);
//准备TicketReport
TicketReport check4projectYear = new TicketReport();
TicketReport check4projectQuarter = new TicketReport();
TicketReport check4projectMonth = new TicketReport();
TicketReport check4projectDay = new TicketReport();
TicketReport check4buildingYear = new TicketReport();
TicketReport check4buildingQuarter = new TicketReport();
TicketReport check4buildingMonth = new TicketReport();
TicketReport check4buildingDay = new TicketReport();
TicketReport check4layoutYear = new TicketReport();
TicketReport check4layoutQuarter = new TicketReport();
TicketReport check4layoutMonth = new TicketReport();
TicketReport check4layoutDay = new TicketReport();
//将日期分类转换为固定格式
Date date = checkTicket.getCheckDate();
String yearFormat = ConvertUtils.convertDate2Year(date);
String quarterFormat = ConvertUtils.convertDate2Quarter(date);
String monthFormat = ConvertUtils.convertDate2Month(date);
String dayFormat = ConvertUtils.convertDate2Day(date);
//优化注入,缓存预算表信息 key->project_id,layout_id,type_date value->budget
Map<String,Integer> budgetMap = new HashMap<>();
List<Budget> budgetList = budgetMapper.getAllBudget2Map();
for (Budget budget:budgetList) {
budgetMap.put(budget.getProjectId()+","+budget.getLayoutId()+","+budget.getTypeDate(),
Integer.valueOf(budget.getBudget()));
}
//根据业态分类 Project_Level为0
//判断Map中是否存在该业态
if(layoutCheckMap.containsKey(mcheckTicket.getLayoutId())){
/*
存在,判断日期是否存在,需要累加的一个参数
1.检票数量InCount->TicketCount
*/
if(layoutCheckMap4Date.containsKey(mcheckTicket.getLayoutId()+","+yearFormat)){
//System.out.println("==============业态年份存在数据累加");
comp5(layoutCheckMap4Date,checkTicket,yearFormat,0,mcheckTicket,budgetMap);
}else{
//年份不存在,添加
//System.out.println("==============年份不存在添加");
comp6(layoutCheckMap4Date,checkTicket,check4layoutYear,yearFormat,0,4,mcheckTicket,budgetMap);
}
if(layoutCheckMap4Date.containsKey(mcheckTicket.getLayoutId()+","+quarterFormat)){
//System.out.println("==============业态季度存在数据累加");
//季度存在,累加数据
comp5(layoutCheckMap4Date,checkTicket,quarterFormat,0,mcheckTicket,budgetMap);
}else{
//季度不存在,添加
//System.out.println("==============季度不存在添加");
comp6(layoutCheckMap4Date,checkTicket,check4layoutQuarter,quarterFormat,0,3,mcheckTicket,budgetMap);
}
if(layoutCheckMap4Date.containsKey(mcheckTicket.getLayoutId()+","+monthFormat)){
//System.out.println("==============业态月份存在数据累加");
//月份存在,累加数据
comp5(layoutCheckMap4Date,checkTicket,monthFormat,0,mcheckTicket,budgetMap);
}else{
//System.out.println("==============月份不存在添加");
//月份不存在,添加
comp6(layoutCheckMap4Date,checkTicket,check4layoutMonth,monthFormat,0,2,mcheckTicket,budgetMap);
}
if(layoutCheckMap4Date.containsKey(mcheckTicket.getLayoutId()+","+dayFormat)){
//System.out.println("==============业态天存在数据累加");
//天存在,累加数据
comp5(layoutCheckMap4Date,checkTicket,dayFormat,0,mcheckTicket,budgetMap);
}else{
//System.out.println("==============天不存在添加");
//天不存在,添加
comp6(layoutCheckMap4Date,checkTicket,check4layoutDay,dayFormat,0,1,mcheckTicket,budgetMap);
}
}else{
//System.out.println("==============0检票业态初始化数据");
//业态不存在,初始化数据
comp6(layoutCheckMap4Date,checkTicket,check4layoutYear,yearFormat,0,4,mcheckTicket,budgetMap);
comp6(layoutCheckMap4Date,checkTicket,check4layoutQuarter,quarterFormat,0,3,mcheckTicket,budgetMap);
comp6(layoutCheckMap4Date,checkTicket,check4layoutMonth,monthFormat,0,2,mcheckTicket,budgetMap);
comp6(layoutCheckMap4Date,checkTicket,check4layoutDay,dayFormat,0,1,mcheckTicket,budgetMap);
//装载
layoutCheckMap4Date.put(mcheckTicket.getLayoutId()+","+yearFormat,check4layoutYear);
layoutCheckMap4Date.put(mcheckTicket.getLayoutId()+","+quarterFormat,check4layoutQuarter);
layoutCheckMap4Date.put(mcheckTicket.getLayoutId()+","+monthFormat,check4layoutMonth);
layoutCheckMap4Date.put(mcheckTicket.getLayoutId()+","+dayFormat,check4layoutDay);
}
layoutCheckMap.put(mcheckTicket.getLayoutId(),null);
//根据业态分类 Project_Level为1
//判断Map中是否存在该商铺
if(buildingCheckMap.containsKey(mcheckTicket.getBuildingCode())){
/*
存在,判断日期是否存在,需要累加的一个参数
1.检票数量InCount->TicketCount
*/
if(buildingCheckMap4Date.containsKey(mcheckTicket.getBuildingCode()+","+yearFormat)){
//System.out.println("==============商铺年份存在数据累加");
comp5(buildingCheckMap4Date,checkTicket,yearFormat,1,mcheckTicket,budgetMap);
}else{
//年份不存在,添加
//System.out.println("==============年份不存在添加");
comp6(buildingCheckMap4Date,checkTicket,check4buildingYear,yearFormat,1,4,mcheckTicket,budgetMap);
}
if(buildingCheckMap4Date.containsKey(mcheckTicket.getBuildingCode()+","+quarterFormat)){
//System.out.println("==============商铺季度存在数据累加");
//季度存在,累加数据
comp5(buildingCheckMap4Date,checkTicket,quarterFormat,1,mcheckTicket,budgetMap);
}else{
//季度不存在,添加
//System.out.println("==============季度不存在添加");
comp6(buildingCheckMap4Date,checkTicket,check4buildingQuarter,quarterFormat,1,3,mcheckTicket,budgetMap);
}
if(buildingCheckMap4Date.containsKey(mcheckTicket.getBuildingCode()+","+monthFormat)){
//System.out.println("==============商铺月份存在数据累加");
//月份存在,累加数据
comp5(buildingCheckMap4Date,checkTicket,monthFormat,1,mcheckTicket,budgetMap);
}else{
//System.out.println("==============月份不存在添加");
//月份不存在,添加
comp6(buildingCheckMap4Date,checkTicket,check4buildingMonth,monthFormat,1,2,mcheckTicket,budgetMap);
}
if(buildingCheckMap4Date.containsKey(mcheckTicket.getBuildingCode()+","+dayFormat)){
//System.out.println("==============商铺天存在数据累加");
//天存在,累加数据
comp5(buildingCheckMap4Date,checkTicket,dayFormat,1,mcheckTicket,budgetMap);
}else{
//System.out.println("==============天不存在添加");
//天不存在,添加
comp6(buildingCheckMap4Date,checkTicket,check4buildingDay,dayFormat,1,1,mcheckTicket,budgetMap);
}
}else{
//System.out.println("==============1检票业态初始化数据");
//业态不存在,初始化数据
comp6(buildingCheckMap4Date,checkTicket,check4buildingYear,yearFormat,1,4,mcheckTicket,budgetMap);
comp6(buildingCheckMap4Date,checkTicket,check4buildingQuarter,quarterFormat,1,3,mcheckTicket,budgetMap);
comp6(buildingCheckMap4Date,checkTicket,check4buildingMonth,monthFormat,1,2,mcheckTicket,budgetMap);
comp6(buildingCheckMap4Date,checkTicket,check4buildingDay,dayFormat,1,1,mcheckTicket,budgetMap);
//装载
buildingCheckMap4Date.put(mcheckTicket.getBuildingCode()+","+yearFormat,check4buildingYear);
buildingCheckMap4Date.put(mcheckTicket.getBuildingCode()+","+quarterFormat,check4buildingQuarter);
buildingCheckMap4Date.put(mcheckTicket.getBuildingCode()+","+monthFormat,check4buildingMonth);
buildingCheckMap4Date.put(mcheckTicket.getBuildingCode()+","+dayFormat,check4buildingDay);
}
buildingCheckMap.put(mcheckTicket.getBuildingCode(),null);
//根据业态分类 Project_Level为2
//判断Map中是否存在该项目
if(projectCheckMap.containsKey(checkTicket.getProjectId())){
/*
存在,判断日期是否存在,需要累加的一个参数
1.检票数量InCount->TicketCount
*/
if(projectCheckMap4Date.containsKey(checkTicket.getProjectId()+","+yearFormat)){
//System.out.println("==============项目年份存在数据累加");
comp5(projectCheckMap4Date,checkTicket,yearFormat,2,mcheckTicket,budgetMap);
}else{
//年份不存在,添加
//System.out.println("==============年份不存在添加");
comp6(projectCheckMap4Date,checkTicket,check4projectYear,yearFormat,2,4,mcheckTicket,budgetMap);
}
if(projectCheckMap4Date.containsKey(checkTicket.getProjectId()+","+quarterFormat)){
//System.out.println("==============项目季度存在数据累加");
//季度存在,累加数据
comp5(projectCheckMap4Date,checkTicket,quarterFormat,2,mcheckTicket,budgetMap);
}else{
//季度不存在,添加
//System.out.println("==============季度不存在添加");
comp6(projectCheckMap4Date,checkTicket,check4projectQuarter,quarterFormat,2,3,mcheckTicket,budgetMap);
}
if(projectCheckMap4Date.containsKey(checkTicket.getProjectId()+","+monthFormat)){
//System.out.println("==============项目月份存在数据累加");
//月份存在,累加数据
comp5(projectCheckMap4Date,checkTicket,monthFormat,2,mcheckTicket,budgetMap);
}else{
//System.out.println("==============月份不存在添加");
//月份不存在,添加
comp6(projectCheckMap4Date,checkTicket,check4projectMonth,monthFormat,2,2,mcheckTicket,budgetMap);
}
if(projectCheckMap4Date.containsKey(checkTicket.getProjectId()+","+dayFormat)){
//System.out.println("==============项目天存在数据累加");
//天存在,累加数据
comp5(projectCheckMap4Date,checkTicket,dayFormat,2,mcheckTicket,budgetMap);
}else{
//System.out.println("==============天不存在添加");
//天不存在,添加
comp6(projectCheckMap4Date,checkTicket,check4projectDay,dayFormat,2,1,mcheckTicket,budgetMap);
}
}else{
//System.out.println("==============2检票业态初始化数据");
//业态不存在,初始化数据
comp6(projectCheckMap4Date,checkTicket,check4projectYear,yearFormat,2,4,mcheckTicket,budgetMap);
comp6(projectCheckMap4Date,checkTicket,check4projectQuarter,quarterFormat,2,3,mcheckTicket,budgetMap);
comp6(projectCheckMap4Date,checkTicket,check4projectMonth,monthFormat,2,2,mcheckTicket,budgetMap);
comp6(projectCheckMap4Date,checkTicket,check4projectDay,dayFormat,2,1,mcheckTicket,budgetMap);
//装载
projectCheckMap4Date.put(checkTicket.getProjectId()+","+yearFormat,check4projectYear);
projectCheckMap4Date.put(checkTicket.getProjectId()+","+quarterFormat,check4projectQuarter);
projectCheckMap4Date.put(checkTicket.getProjectId()+","+monthFormat,check4projectMonth);
projectCheckMap4Date.put(checkTicket.getProjectId()+","+dayFormat,check4projectDay);
}
projectCheckMap.put(checkTicket.getProjectId(),null);
}
}
//project
filterMap4check(projectCheckMap,projectCheckMap4Date);
//layout
filterMap4check(layoutCheckMap,layoutCheckMap4Date);
//building
filterMap4check(buildingCheckMap,buildingCheckMap4Date);
//注入到mysql
for (Map.Entry<String,Map<String,TicketReport>> layout:layoutCheckMap.entrySet()) {
for (Map.Entry<String,TicketReport> layout4Date:layout.getValue().entrySet()) {
TicketReport ticket = layout4Date.getValue();
ticketReportMapper.insert(ticket);
}
}
for (Map.Entry<String,Map<String,TicketReport>> project:projectCheckMap.entrySet()) {
for (Map.Entry<String,TicketReport> project4Date:project.getValue().entrySet()) {
TicketReport ticket = project4Date.getValue();
ticketReportMapper.insert(ticket);
}
}
for (Map.Entry<String,Map<String,TicketReport>> build:buildingCheckMap.entrySet()) {
for (Map.Entry<String,TicketReport> build4Date:build.getValue().entrySet()) {
TicketReport ticket = build4Date.getValue();
ticketReportMapper.insert(ticket);
}
}
return 0;
}
@Override
public int saveBatchInfo() {
//从mongo拉取批次信息
List<MShopSaleDataSeq> seqList = mongoTemplate.findAll(MShopSaleDataSeq.class);
for (MShopSaleDataSeq mShopSaleDataSeq:seqList) {
//判断批次号是否存在
String seqId = mShopSaleDataSeq.getSeqId();
List<Batch> batchBySeqId = batchMapper.findBatchBySeqId(seqId);
//若批次表存在,跳过
if(batchBySeqId!=null&&batchBySeqId.size()!=0){
continue;
}
//注入批次表
Batch batch = new Batch();
batch.setBatchNumber(mShopSaleDataSeq.getSeqId());
batch.setCreateDate(ConvertUtils.convertDate(mShopSaleDataSeq.getSys_time()));
batch.setLayoutId(Integer.valueOf(mShopSaleDataSeq.getLayoutId()));
batch.setLayoutName(mShopSaleDataSeq.getLayoutName());
batch.setTotalCount(Integer.valueOf(mShopSaleDataSeq.getTotalCount()));
batch.setPageTotal(Integer.valueOf(mShopSaleDataSeq.getPageTotal()));
//默认为未统计
batch.setStatisticsState("N");
batch.setGetCount(0);
//标记为未获取
batch.setGetState("N");
//注入到Mysql
batchMapper.insert(batch);
}
return 0;
}
@Override
public void AnalyzeData4CheckTicket() {
}
@Override
public void AnalyzeData4ShopSale() {
}
private void comp(Map<String,IncomeReport> map, TicketSale ticketSale, String format,int pLevel,MticketSaleDetail mticketSaleDetail) throws Exception{
IncomeReport incomeReport = null;
if(pLevel==0)//业态
incomeReport = map.get(ticketSale.getLayoutId()+","+format);
if(pLevel==1)//商铺
incomeReport = map.get(mticketSaleDetail.getBuildingCode()+","+format);
if(pLevel==2)//项目
incomeReport = map.get(ticketSale.getProjectId()+","+format);
//年存在,累加数据
if(incomeReport!=null){
BigDecimal typeAmount = incomeReport.getTypeAmount();
typeAmount = typeAmount.add(ticketSale.getTicketAmount());
Integer bookingCount = incomeReport.getBookingCount();
Integer ticketCount = ticketSale.getTicketCount();
bookingCount+=ticketCount;
incomeReport.setTypeAmount(typeAmount);
incomeReport.setBookingCount(bookingCount);
}
//覆盖key-value
if(pLevel==0){
//业态
map.put(ticketSale.getLayoutId()+","+format,incomeReport);
}
if(pLevel==1){
//商铺
map.put(mticketSaleDetail.getBuildingCode()+","+format,incomeReport);
}
if(pLevel==2){
//项目
map.put(ticketSale.getProjectId()+","+format,incomeReport);
}
}
private void comp2(Map<String,IncomeReport> map, TicketSale ticketSale, IncomeReport report, String format, int pLevel, int type, MticketSaleDetail mticketSaleDetail) throws Exception{
report.setProjectLevel(pLevel);
if(pLevel==2){
//项目
//System.out.println("comp2-->pLevel:2");
report.setTypeId(ticketSale.getProjectId());
report.setTypeName(ticketSale.getProjectName());
}else if(pLevel==1){
//商铺
//System.out.println("comp2-->pLevel:1");
report.setTypeId(mticketSaleDetail.getBuildingCode());
report.setTypeName(mticketSaleDetail.getBuildingName());
}else if(pLevel==0){
//业态
//System.out.println("comp2-->pLevel:1");
report.setTypeId(ticketSale.getLayoutId().toString());
report.setTypeName(ticketSale.getLayoutName());
}
report.setTypeAmount(ticketSale.getTicketAmount());
report.setDateType(format);
report.setType(type);
//income4year.setBudgetId(budgetId); 这个没用直接去budget表取
//销售比率 该项目销售额/所有项目销售额
//income4year.setSalePercentum();//需要统计完成计算
//初始化售票总数
report.setBookingCount(ticketSale.getTicketCount());
report.setCreateDate(new Date());
map.put(report.getTypeId()+","+format,report);
}
private void comp3(Map<String, IncomeReport> map, ShopSale sale, String format,int pLevel,MShopSaleDetail mShopSaleDetail) throws Exception {
IncomeReport incomeReport = null;
if(pLevel==0)//业态
incomeReport = map.get(sale.getLayoutId()+","+format);
if(pLevel==1)//商铺
incomeReport = map.get(mShopSaleDetail.getBuildingCode()+","+format);
if(pLevel==2)//项目
incomeReport = map.get(sale.getProjectId()+","+format);
//年存在,累加数据
if(incomeReport!=null){
BigDecimal typeAmount = incomeReport.getTypeAmount();
typeAmount = typeAmount.add(sale.getSalePrice());
incomeReport.setTypeAmount(typeAmount);
}
//覆盖key-value
if(pLevel==0){
//业态
map.put(sale.getLayoutId()+","+format,incomeReport);
}
if(pLevel==1){
//商铺
map.put(mShopSaleDetail.getBuildingCode()+","+format,incomeReport);
}
if(pLevel==2){
//项目
map.put(sale.getProjectId()+","+format,incomeReport);
}
}
private void comp4(Map<String, IncomeReport> map, ShopSale sale, IncomeReport report, String format, int pLevel, int type, MShopSaleDetail mShopSaleDetail) {
report.setProjectLevel(pLevel);
if(pLevel==2){
//项目
//System.out.println("comp4-->pLevel:2");
report.setTypeId(sale.getProjectId());
report.setTypeName(sale.getProjectName());
}else if(pLevel==1){
//商铺
//System.out.println("comp4-->pLevel:1");
report.setTypeId(mShopSaleDetail.getBuildingCode());
report.setTypeName(mShopSaleDetail.getBuildingName());
}else if(pLevel==0){
//业态
// System.out.println("comp4-->pLevel:0");
String layoutId = sale.getLayoutId().toString();
report.setTypeId(layoutId);
report.setTypeName(sale.getLayoutName());
}
report.setTypeAmount(sale.getSalePrice());
report.setDateType(format);
report.setType(type);
//income4year.setBudgetId(budgetId); 这个没用直接去budget表取
//销售比率 该项目销售额/所有项目销售额
//income4year.setSalePercentum();//需要统计完成计算
//初始化售票总数
report.setCreateDate(new Date());
map.put(report.getTypeId()+","+format,report);
}
private void comp5(Map<String,TicketReport> map,CheckTicket checkTicket,String format,int pLevel,McheckTicket mcheckTicket,
Map<String,Integer> budgetMap){
TicketReport ticketReport = new TicketReport();
int checkCount;
int totalNum = 0;
if(pLevel==0)//业态
ticketReport = map.get(mcheckTicket.getLayoutId()+","+format);
if(pLevel==1)//商铺
ticketReport = map.get(mcheckTicket.getBuildingCode()+","+format);
if(pLevel==2)//项目
ticketReport = map.get(checkTicket.getProjectId()+","+format);
String layoutId = mcheckTicket.getLayoutId();
String projectId = checkTicket.getProjectId();
//累加数据 检票数量
checkCount = ticketReport.getTicketCount();
checkCount+=checkTicket.getCheckCount();
ticketReport.setTicketCount(checkCount);
//覆盖key-value
if(pLevel==0){
//业态
for (Map.Entry<String,Integer> entry:budgetMap.entrySet()) {
String layoutInMap = entry.getKey().split(",")[1];
String typeDateInMap = entry.getKey().split(",")[2];
if(layoutId.equals(layoutInMap)&&format.equals(typeDateInMap)){
totalNum += entry.getValue();
}
}
if(totalNum!=0)
ticketReport.setFinishPercentum(ticketReport.getTicketCount()*100/totalNum);
else
ticketReport.setFinishPercentum(0);
map.put(mcheckTicket.getLayoutId()+","+format,ticketReport);
}
if(pLevel==1){
//商铺
for (Map.Entry<String,Integer> entry:budgetMap.entrySet()) {
String typeDateInMap = entry.getKey().split(",")[2];
if(format.equals(typeDateInMap)){
totalNum += entry.getValue();
}
}
if(totalNum!=0)
ticketReport.setFinishPercentum(ticketReport.getTicketCount()*100/totalNum);
else
ticketReport.setFinishPercentum(0);
map.put(mcheckTicket.getBuildingCode()+","+format,ticketReport);
}
if(pLevel==2){
//项目
for (Map.Entry<String,Integer> entry:budgetMap.entrySet()) {
String typeDateInMap = entry.getKey().split(",")[2];
String projectInMap = entry.getKey().split(",")[0];
if(projectId.equals(projectInMap)&&format.equals(typeDateInMap)){
totalNum += entry.getValue()+0+0;
}
}
if(totalNum!=0)
ticketReport.setFinishPercentum(ticketReport.getTicketCount()*100/totalNum);
else
ticketReport.setFinishPercentum(0);
map.put(checkTicket.getProjectId()+","+format,ticketReport);
}
}
private void comp6(Map<String, TicketReport> map, CheckTicket checkTicket, TicketReport report, String format, int pLevel, int type, McheckTicket mcheckTicket,
Map<String,Integer> budgetMap){
int totalNum =0;
report.setProjectLevel(pLevel);
report.setTicketCount(checkTicket.getCheckCount());
String projectId = checkTicket.getProjectId();
String layoutId = mcheckTicket.getLayoutId();
if(pLevel==2){
//项目
//System.out.println("comp6-->pLevel:2");
report.setTypeId(checkTicket.getProjectId());
report.setTypeName(checkTicket.getProjectName());
for (Map.Entry<String,Integer> entry:budgetMap.entrySet()) {
String typeDateInMap = entry.getKey().split(",")[2];
String projectInMap = entry.getKey().split(",")[0];
if(projectId.equals(projectInMap)&&format.equals(typeDateInMap)){
totalNum += entry.getValue();
}
}
}else if(pLevel==1){
//商铺
//System.out.println("comp6-->pLevel:1");
report.setTypeId(mcheckTicket.getBuildingCode());
report.setTypeName(mcheckTicket.getBuildingName());
//商铺
for (Map.Entry<String,Integer> entry:budgetMap.entrySet()) {
String typeDateInMap = entry.getKey().split(",")[2];
if(format.equals(typeDateInMap)){
totalNum += entry.getValue();
}
}
}else if(pLevel==0){
//业态
//System.out.println("comp6-->pLevel:0");
report.setTypeId(mcheckTicket.getLayoutId());
report.setTypeName(layoutMapper.selectByPrimaryKey(Integer.valueOf(mcheckTicket.getLayoutId())).getLayoutName());
for (Map.Entry<String,Integer> entry:budgetMap.entrySet()) {
String layoutInMap = entry.getKey().split(",")[1];
String typeDateInMap = entry.getKey().split(",")[2];
if(layoutId.equals(layoutInMap)&&format.equals(typeDateInMap)){
totalNum += entry.getValue()+0;
}
}
}
report.setDateType(format);
report.setType(type);
//report.setBudgetId(budgetId); 这个没用直接去budget表取
//report.setRetentionNumber(); 滞留数没定义
//完成率 检票数/目标
if(totalNum!=0)
report.setFinishPercentum(report.getTicketCount()*100/totalNum);
else
report.setFinishPercentum(0);
report.setCreateDate(new Date());
map.put(report.getTypeId()+","+format,report);
}
private void filterMap(Map<String,Map<String,IncomeReport>> bmap,Map<String,IncomeReport> smap){
Map<String,IncomeReport> resMap = null;
for (String key:bmap.keySet()) {
resMap = new HashMap<>();
for (Map.Entry<String,IncomeReport> entry:smap.entrySet()) {
if(key!=null&&key.equals(entry.getValue().getTypeId())){
resMap.put(entry.getKey(),entry.getValue());
}
}
bmap.put(key,resMap);
}
}
private void filterMap4check(Map<String,Map<String,TicketReport>> bmap,Map<String,TicketReport> smap){
Map<String,TicketReport> resMap = null;
for (String key:bmap.keySet()) {
resMap = new HashMap<>();
for (Map.Entry<String,TicketReport> entry:smap.entrySet()) {
if(key!=null&&key.equals(entry.getValue().getTypeId())){
resMap.put(entry.getKey(),entry.getValue());
}
}
bmap.put(key,resMap);
}
}
private void salePercentCalc(Map<String,IncomeReport> allMap){
for (String str:allMap.keySet()) {
//总金额
BigDecimal total = new BigDecimal(0.0);
//固定类型金额
BigDecimal money = new BigDecimal(0.0);
for (Map.Entry<String,IncomeReport> judgeEntry:allMap.entrySet()) {
if(str.split(",")[1].equals(judgeEntry.getValue().getDateType())){
//指定时间的总金额
total = total.add(judgeEntry.getValue().getTypeAmount());
}
if(str.equals(judgeEntry.getKey())){
money = judgeEntry.getValue().getTypeAmount();
}
}
BigDecimal hun = new BigDecimal(100);
allMap.get(str).setSalePercentum(money.multiply(hun).divide(total,2,BigDecimal.ROUND_HALF_UP).toString());
}
}
@Override
public void clearData() {
incomeReportMapper.clearAll();
shopSaleMapper.clearAll();
ticketSaleMapper.clearAll();
checkTicketMapper.clearAll();
ticketReportMapper.clearAll();
}
}
| 67,411 | 0.563798 | 0.551173 | 1,172 | 52.86348 | 33.772427 | 188 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.271331 | false | false | 9 |
ad291c3134ab54ca6e7eed3bdd29c28dbf56172d | 9,509,057,640,722 | 41d09159a7f7c2a8f8004a816dea5d0eef786129 | /app/src/main/java/com/example/kerish/android_recyclerview/MainActivity.java | 27be693b6f47231b3490ece0fede5b1227184c9b | [] | no_license | skerish/RecyclerView | https://github.com/skerish/RecyclerView | a355c34bf74a1711bf05b5a784670ca5fd9c1205 | 1b38e31f9fccc2cd2158a236bc620468b6d63817 | refs/heads/master | 2020-04-23T19:16:12.432000 | 2019-02-19T03:22:17 | 2019-02-19T03:22:17 | 171,397,460 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.kerish.android_recyclerview;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView recyclerView = (RecyclerView)findViewById(R.id.recycler_id);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
String[] lang = {"Java", "JavaScript", "C#", "C++", "php", "C", "Python",
"Go","Java", "JavaScript", "C#", "C++", "php", "C", "Python", "Go"};
recyclerView.setAdapter(new ProgrammingAdapter(lang));
}
}
| UTF-8 | Java | 840 | java | MainActivity.java | Java | [
{
"context": "package com.example.kerish.android_recyclerview;\n\nimport android.support.v7.",
"end": 26,
"score": 0.9674734473228455,
"start": 20,
"tag": "USERNAME",
"value": "kerish"
}
] | null | [] | package com.example.kerish.android_recyclerview;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView recyclerView = (RecyclerView)findViewById(R.id.recycler_id);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
String[] lang = {"Java", "JavaScript", "C#", "C++", "php", "C", "Python",
"Go","Java", "JavaScript", "C#", "C++", "php", "C", "Python", "Go"};
recyclerView.setAdapter(new ProgrammingAdapter(lang));
}
}
| 840 | 0.695238 | 0.691667 | 25 | 32.599998 | 30.046631 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.04 | false | false | 9 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.